JavaScript使ifram跨域相互访问及与PHP通信的实例_javascript技巧

风浩吖_8246

风浩吖_8246

2016-05-16

2345人浏览

原创

olor:#f60; text-decoration:underline;" title= "html"href="https://m.php.cn/zt/15763.html" target="_blank">html4/loose.dtd">

iframe 与主框架相互访问方法

1.同域相互访问

假设A.html 与 b.html domain都是localhost (同域)
A.html中iframe 嵌入 B.html,name=myframe
A.html有js function fMain()
B.html有js function fIframe()
需要实现 A.html 调用 B.html 的 fIframe(),B.html 调用 A.html 的 fMain()

A.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> main window </title><script type="text/javascript"> 
 // main js function 
 function fMain(){ 
 alert('main function execute success'); 
 } 
 
 // exec iframe function 
 function exec_iframe(){ 
 window.myframe.fIframe(); 
 } 
 </script><p>A.html main</p> 
 <p><input type="button" value="exec iframe function" onclick="exec_iframe()"></p> 
 <iframe src="B.html" name="myframe" width="100%" height="100"></iframe> 
  
 



<p>B.html</p>
<div class="jb51code">
<pre class="brush:js;">
 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> iframe window </title><script type="text/javascript"> 
 // iframe js function 
 function fIframe(){ 
 alert('iframe function execute success'); 
 } 
 
 // exec main function 
 function exec_main(){ 
 parent.fMain(); 
 } 
 </script><p>B.html iframe</p> 
 <p><input type="button" value="exec main function" onclick="exec_main()"></p><div class="aritcle_card flexRow artxards">
											<div class="artcardd flexRow">
												<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill10828" title="财经HTML高端海报生成"><img
														src="https://img.php.cn/upload/skill/000/000/081/179336525482166.jpg" alt="财经HTML高端海报生成" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
												<div class="aritcle_card_info flexColumn">
													<a rel="nofollow" href="/xiazai/skill10828" title="财经HTML高端海报生成" class="overflowclass">财经HTML高端海报生成</a>
													<p class="overflowclass">复杂得财经如何变成清晰,适合手机看的海报?如何加上你的IP</p>
												</div>
												<a rel="nofollow" href="/xiazai/skill10828" title="财经HTML高端海报生成" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
												</a>
											</div>
										</div> 
  
 

点击A.html 的 exec iframe function button,执行成功,弹出iframe function execute success。如下图

201633165209664.jpg (537×208)

点击B.html 的 exec main function button,执行成功,弹出 main function execute success。如下图

201633165228804.jpg (536×208)

2.跨域互相访问

假设 A.html domain是 localhost, B.html domain 是 127.0.0.1 (跨域)
这里使用 localhost 与 127.0.0.1 只是方便测试,localhost 与 127.0.0.1已经不同一个域,因此执行效果是一样的。
实际使用时换成 www.domaina.com 与 www.domainb.com 即可。
A.html中iframe 嵌入 B.html,name=myframe
A.html有js function fMain()
B.html有js function fIframe()
需要实现 A.html 调用 B.html 的 fIframe(),B.html 调用 A.html 的 fMain() (跨域调用)

如果使用上面同域的方法,浏览器判断A.html 与 B.html 不同域,会有错误提示。
Uncaught SecurityError: Blocked a frame with origin "http://localhost" from accessing a frame with origin "http://127.0.0.1". Protocols, domains, and ports must match.

实现原理:
因为浏览器为了安全,禁止了不同域访问。因此只要调用与执行的双方是同域则可以相互访问。

首先,A.html 如何调用B.html的 fIframe方法
1.在A.html 创建一个 iframe
2.iframe的页面放在 B.html 同域下,命名为execB.html
3.execB.html 里有调用B.html fIframe方法的js调用

<script type="text/javascript"> 
parent.window.myframe.fIframe(); // execute parent myframe fIframe function 
</script>

这样A.html 就能通过 execB.html 调用 B.html 的 fIframe 方法了。

同理,B.html 需要调用A.html fMain方法,需要在B.html 嵌入与A.html 同域的 execA.html
execA.html 里有调用 A.html fMain 方法的js 调用

<script type="text/javascript"> 
parent.parent.fMain(); // execute main function 
</script>

这样就能实现 A.html 与 B.html 跨域相互调用。

A.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> main window </title><script type="text/javascript"> 
 
 // main js function 
 function fMain(){ 
 alert('main function execute success'); 
 } 
 
 // exec iframe function 
 function exec_iframe(){ 
 if(typeof(exec_obj)=='undefined'){ 
  exec_obj = document.createElement('iframe'); 
  exec_obj.name = 'tmp_frame'; 
  exec_obj.src = 'http://127.0.0.1/execB.html'; 
  exec_obj.style.display = 'none'; 
  document.body.appendChild(exec_obj); 
 }else{ 
  exec_obj.src = 'http://127.0.0.1/execB.html?' + Math.random(); 
 } 
 } 
 </script><p>A.html main</p> 
 <p><input type="button" value="exec iframe function" onclick="exec_iframe()"></p> 
 <iframe src="http://127.0.0.1/B.html" name="myframe" width="100%" height="100"></iframe> 
  
 

B.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> iframe window </title><script type="text/javascript"> 
 // iframe js function 
 function fIframe(){ 
 alert('iframe function execute success'); 
 } 
 
 // exec main function 
 function exec_main(){ 
 if(typeof(exec_obj)=='undefined'){ 
  exec_obj = document.createElement('iframe'); 
  exec_obj.name = 'tmp_frame'; 
  exec_obj.src = 'http://localhost/execA.html'; 
  exec_obj.style.display = 'none'; 
  document.body.appendChild(exec_obj); 
 }else{ 
  exec_obj.src = 'http://localhost/execA.html?' + Math.random(); 
 } 
 } 
 </script><p>B.html iframe</p> 
 <p><input type="button" value="exec main function" onclick="exec_main()"></p> 
  
 

execA.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> exec main function </title><script type="text/javascript"> 
  parent.parent.fMain(); // execute main function 
 </script>

execB.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> exec iframe function </title><script type="text/javascript"> 
  parent.window.myframe.fIframe(); // execute parent myframe fIframe function 
 </script>

执行如下图:

201633165339112.jpg (529×214)


php main 与 iframe 相互通讯类(同域/跨域)
把main与iframe相互通讯的方法封装成类,主要有两个文件,
JS:FrameMessage.js 实现调用方法的接口,如跨域则创建临时iframe,调用同域执行者。
PHP:FrameMessage.class.php 实现接收到跨域请求时,根据参数返回执行方法的JS code。

功能如下:
1.支持同域与跨域通讯
2.传递的方法参数支持字符串,JSON,数组等。

201633165429252.jpg (549×249)

复制代码 代码如下:
FrameMessage.exec('http://127.0.0.1/execB.php', 'myframe', 'fIframe', ['fdipzone', '{"gender":"male","age":"29"}', '["http://blog.csdn.net/fdipzone", "http://weibo.com/fdipzone"]']); 

201633170000506.jpg (527×242)

复制代码 代码如下:
FrameMessage.exec('http://localhost/execA.php', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']);

FrameMessage.js

/** Main 与 Iframe 相互通讯类 支持同域与跨域通讯 
* Date: 2013-12-29 
* Author: fdipzone 
* Ver: 1.0 
*/ 
var FrameMessage = (function(){ 
 
 this.oFrameMessageExec = null; // 临时iframe 
 
 /* 执行方法 
 executor 执行的页面,为空则为同域 
 frame 要调用的方法的框架名称,为空则为parent 
 func  要调用的方法名 
 args  要调用的方法的参数,必须为数组[arg1, arg2, arg3, argn...],方便apply调用 
    元素为字符串格式,请不要使用html,考虑注入安全的问题会过滤 
 */ 
 this.exec = function(executor, frame, func, args){ 
 
  this.executor = typeof(executor)!='undefined'? executor : ''; 
  this.frame = typeof(frame)!='undefined'? frame : ''; 
  this.func = typeof(func)!='undefined'? func : ''; 
  this.args = typeof(args)!='undefined'? (__fIsArray(args)? args : []) : []; // 必须是数组 
 
  if(executor==''){ 
   __fSameDomainExec(); // same domain 
  }else{ 
   __fCrossDomainExec(); // cross domain 
  } 
 
 } 
 
 /* 同域执行 */ 
 function __fSameDomainExec(){ 
  if(this.frame==''){ // parent 
   parent.window[this.func].apply(this, this.args); 
  }else{ 
   window.frames[this.frame][this.func].apply(this, this.args); 
  } 
 } 
 
 /* 跨域执行 */ 
 function __fCrossDomainExec(){ 
  if(this.oFrameMessageExec == null){ 
   this.oFrameMessageExec = document.createElement('iframe'); 
   this.oFrameMessageExec.name = 'FrameMessage_tmp_frame'; 
   this.oFrameMessageExec.src = __fGetSrc(); 
   this.oFrameMessageExec.style.display = 'none'; 
   document.body.appendChild(this.oFrameMessageExec); 
  }else{ 
   this.oFrameMessageExec.src = __fGetSrc(); 
  } 
 } 
 
 /* 获取执行的url */ 
 function __fGetSrc(){ 
  return this.executor + (this.executor.indexOf('?')==-1? '?' : '&') + 'frame=' + this.frame + '&func=' + this.func + '&args=' + JSON.stringify(this.args) + '&framemessage_rand=' + Math.random(); 
 } 
 
 /* 判断是否数组 */ 
 function __fIsArray(obj){ 
  return Object.prototype.toString.call(obj) === '[object Array]'; 
 } 
 
 return this; 
 
}()); 

FrameMessage.class.php

'."
"; 
  $ret .= $str."
"; 
  $ret .= ''; 
 
  return $ret; 
 } 
 
 
 /** 转义参数 
 * @param String $str 
 * @return String 
 */ 
 private static function jsFormat($str){ 
 
  $str = strip_tags(trim($str)); // 过滤html 
  $str = str_replace('\s\s', '\s', $str); 
  $str = str_replace(chr(10), '', $str); 
  $str = str_replace(chr(13), '', $str); 
  $str = str_replace(' ', '', $str); 
  $str = str_replace('\', '\\', $str); 
  $str = str_replace('"', '\"', $str); 
  $str = str_replace('\'', '\\'', $str); 
  $str = str_replace("'", "'", $str); 
 
  return $str; 
 } 
 
} // class end 
 
?> 

A.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> main window </title><script type="text/javascript" src="json2.js"></script><script type="text/javascript" src="FrameMessage.js"></script><script type="text/javascript"> 
 
 // main js function 
 function fMain(profession, skill, company){ 
 
 var skill_p = JSON.parse(skill); 
 var company_p = JSON.parse(company); 
  
 var msg = "main function execute success

"; 
 msg += "profession:" + profession + "
"; 
 msg += "first skill:" + skill_p.first + "
"; 
 msg += "second skill:" + skill_p.second + "
"; 
 msg += "company1:" + company_p[0] + "
"; 
 msg += "company2:" + company_p[1] + "
"; 
 
 alert(msg); 
 
 } 
 
 // exec iframe function 
 function exec_iframe(){ 
 // same domain 
 //FrameMessage.exec('', 'myframe', 'fIframe', ['fdipzone', '{"gender":"male","age":"29"}', '["http://blog.csdn.net/fdipzone", "http://weibo.com/fdipzone"]']); 
 
 // cross domain 
 FrameMessage.exec('http://127.0.0.1/execB.php', 'myframe', 'fIframe', ['fdipzone', '{"gender":"male","age":"29"}', '["http://blog.csdn.net/fdipzone", "http://weibo.com/fdipzone"]']); 
 } 
 </script><p>A.html main</p> 
 <p><input type="button" value="exec iframe function" onclick="exec_iframe()"></p> 
 <!-- same domain --> 
 <!--<iframe src="B.html" name="myframe" width="100%" height="100"></iframe>--> 
 <!-- cross domain --> 
 <iframe src="http://127.0.0.1/B.html" name="myframe" width="100%" height="100"></iframe> 
  
 


B.html

 
 
  
 <meta http-equiv="content-type" content="text/html; charset=utf-8"><title> iframe window </title><script type="text/javascript" src="json2.js"></script><script type="text/javascript" src="FrameMessage.js"></script><script type="text/javascript"> 
 
 // iframe js function 
 function fIframe(name, obj, arr){ 
  
 var obj_p = JSON.parse(obj); 
 var arr_p = JSON.parse(arr); 
  
 var msg = "iframe function execute success

"; 
 msg += "name:" + name + "
"; 
 msg += "gender:" + obj_p.gender + "
"; 
 msg += "age:" + obj_p.age + "
"; 
 msg += "blog:" + arr_p[0] + "
"; 
 msg += "weibo:" + arr_p[1] + "
"; 
 
 alert(msg); 
 
 } 
 
 // exec main function 
 function exec_main(){ 
 // same domain 
 //FrameMessage.exec('', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']); 
 
 // cross domain 
 FrameMessage.exec('http://localhost/execA.php', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']); 
 } 
 </script><p>B.html iframe</p> 
 <p><input type="button" value="exec main function" onclick="exec_main()"></p> 
  
 


execA.php 与 execB.php

 

php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

javascript php js html

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Vite 项目如何打包和部署
Vite 项目如何打包和部署

Vite项目打包部署专题汇集生产构建、产物预览、输出目录、资源路径、Nginx与GitHub Pages部署及常见白屏和路由404问题的已审核文章,帮助读者完成上线流程。

2026.10.28

40

16

Vite 如何搭配 Vue.js
Vite 如何搭配 Vue.js

Vite搭配Vue.js专题汇集创建Vue 3项目、配置开发环境、路径别名、Vue插件、代理、多环境构建与调试的已审核文章,帮助读者完成从初始化到日常开发的配置。

2026.10.28

20

15

Vite 项目目录怎么看
Vite 项目目录怎么看

Vite项目目录专题汇集入口文件、src源码、public静态资源、路径别名、项目根目录和构建输出目录相关的已审核文章,帮助读者理解各文件夹的用途与引用方式。

2026.10.28

40

10

Gradle插件开发入门教程
Gradle插件开发入门教程

本专题介绍Gradle插件开发的基本流程,涵盖插件类编写、自定义任务注册、扩展参数设计和插件应用方法,帮助你理解插件如何组织构建逻辑,减少多个项目之间的重复配置。

2026.10.22

120

11

Gradle Wrapper配置教程
Gradle Wrapper配置教程

本专题介绍Gradle Wrapper的基本作用,涵盖文件组成、生成方法、版本配置和任务调用,帮助你理解项目如何使用指定的Gradle版本,减少不同开发环境带来的构建差异。

2026.10.22

80

10

Golangci-lint检查器使用教程
Golangci-lint检查器使用教程

本专题整理Golangci-lint常用Linters的用途与配置方法,覆盖错误处理、无效代码、安全、复杂度、命名和依赖检查,帮助项目合理选规则。

2026.10.22

80

15

Gradle怎么构建Java项目
Gradle怎么构建Java项目

本专题介绍Gradle Java项目构建方法,涵盖Java插件配置、依赖声明、源码编译、测试执行和打包检查,帮助你理解各阶段的任务关系,逐步完成项目构建。

2026.10.22

40

10

PHP时间戳漏洞修复教程
PHP时间戳漏洞修复教程

本专题汇总PHP常见时间戳漏洞,包括2038年溢出、时区漂移、时间戳伪造、重放攻击、时间盲注与日志审计失效等,并给出升级64位环境、使用 DateTimeImmutable、统一UTC、严格超时校验、预处理绑定、hash_equals 比对等修复方案,帮助开发者快速排查和加固时间相关代码。

2026.10.22

80

25

Golangci-lint配置文件与规则设置
Golangci-lint配置文件与规则设置

本专题聚焦Golangci-lint YAML配置文件,讲清运行参数、规则启停、目录排除、问题过滤及严重级别设置,便于团队统一检查标准。

2026.10.22

40

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WebStorm 官方调试文档
WebStorm 官方调试文档

共0课时 | 0人学习

React 教程
React 教程

共58课时 | 12.4万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 6.7万人学习