Home > Web Front-end > JS Tutorial > body text

iframe跨域通信封装详解_jquery

WBOY
Release: 2016-05-16 15:45:45
Original
1250 people have browsed it

iframe跨域通信

查看演示        源码下载

众所周知,由于前端javascript对跨域访问做了安全限制,javascript只能访问与包含它的文档在同一域下的内容。

用法举例:

需求是在http://www.demo.org/top.html中通过iframe方式嵌入http://www.iframe.com/iframe.html,而在iframe页面中希望通过点击一个按钮,调用top页面的一个js方法。

1. 在top页面中建立方法供内部页面使用

复制代码 代码如下:

function testFun (text) {
 alert(text);
}

2. 在http://www.demo.org/top.html中嵌入iframe

复制代码 代码如下:



3. 建立www.demo.org域下建立一个代理页面http://www.demo.org/proxy.html用于跨域通信使用

4. 在http://www.demo.org/proxy.html加入用于代理页面的逻辑

5. 在http://www.iframe.com/iframe.html页面中通过js配置代理页面地址

复制代码 代码如下:

TopProxyConfig = {url:'http://www.demo.org/proxy.html'};

6. 通过kissy加载通信模块

复制代码 代码如下:

KISSY.use('topproxy', function(S, TopProxy){
//执行代码
});

7. 在http://www.iframe.com/iframe.html通过TopProxy.call直接访问http://www.demo.org/top.html中的方法,如

KISSY.use('topproxy', function(S, TopProxy){
 TopProxy.call('testFun', '这是一个真实的故事');
});
Copy after login

其中call方法的第一个参数是外部网页的全局方法名,支持“.”,后面参数无限个,均传到目标方法里去。

注:

1. 调用后可能不会立即执行,会等到iframe加载完毕后才触发,如果想预加载可以提前执行一个没用的方法。
2. 如果不设置TopProxyConfig,那么会认为引用iframe和父iframe同域(大域)并直接调用top对象。
3. 在IE678下可能直接调用top中的系统方法会报错,由于系统方法不支持apply。

原理:

A页面嵌日的iframe页面B,其中B想调用A的方法并传递数据,那么可在B中嵌入A页面同域下的一个iframe页面C,C可以通过window.top访问到A的window。那么在B中可以改变C的href的hash向C传递一些信息,然后C再把这些信息传递给A,从而间接达到B给A传递信息的目的

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!