Javascript 跨域 iframe 通信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1949764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:02:08  来源:igfitidea点击:

Cross-Domain iframe communication

javascriptiframecross-domain

提问by Chris

I have an iframe being created on a page, and the page's domain is being explicitly set to 'xyz.com' but the iframe's domain is defaulting to 'dev.xyz.com', which is the actual domain i'm developing for.

我在页面上创建了一个 iframe,并且页面的域被明确设置为“xyz.com”,但 iframe 的域默认为“dev.xyz.com”,这是我正在开发的实际域。

The problem is, when I try to access that iframe via iframe.contentWindow.document, it fails due to the difference in domain.

问题是,当我尝试通过 iframe.contentWindow.document 访问该 iframe 时,由于域的差异而失败。

I've tried setting the iframe's src to a file with document.domain = 'xyz.com' but that doesn't seem to be doing the trick...

我试过将 iframe 的 src 设置为 document.domain = 'xyz.com' 的文件,但这似乎并没有奏效......

Any ideas?

有任何想法吗?

回答by NVI

Page inside iframe:

iframe 内的页面:

<script>
document.domain = document.domain;
</script>

It looks silly, but it works. See "What does document.domain = document.domain do?".

它看起来很傻,但它有效。请参阅“ document.domain = document.domain 的作用是什么?”。

回答by 0x6A75616E

After some research, I found this jQuery pluginthat makes postMessage backwards-compatible with older browsers using various tricks.

经过一番研究,我发现了这个jQuery 插件,它使用各种技巧使 postMessage 向后兼容旧浏览器。

Here is a quick example showing how to send the height of the iframe's body to the parent window:

这是一个快速示例,展示了如何将 iframe 正文的高度发送到父窗口:

On the host (parent) page:

在主机(父)页面上:

    // executes when a message is received from the iframe, to adjust 
    // the iframe's height
    $.receiveMessage(
        function( event ){
            $( 'my_iframe' ).css({
                height: event.data
            });
    });
   // Please note this function could also verify event.origin and other security-related checks.

On the iframe page:

在 iframe 页面上:

$(function(){

    // Sends a message to the parent window to tell it the height of the 
    // iframe's body        
    var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);

    $.postMessage(
        $('body').outerHeight( true ) + 'px',
        '*',
        target
    );

});

I've tested this on Chrome 13+, Firefox 3.6+, IE7, 8 and 9 on XP and W7, safari on OSX and W7. ;)

我已经在 XP 和 W7 上的 Chrome 13+、Firefox 3.6+、IE7、8 和 9、OSX 和 W7 上的 safari 上测试过这个。;)

回答by Richard

As a addition to the reference to the Ben Alman plug in I thought I would post this working example. It ]rRelies on an iframe which has a source page containing jquery authentication & data query script which then passes the result to {other domain} parent window using the message plugin.

作为对 Ben Alman 插件的参考的补充,我想我会发布这个工作示例。它]r依赖于一个 iframe,它有一个包含 jquery 身份验证和数据查询脚本的源页面,然后使用消息插件将结果传递到 {other domain} 父窗口。

NB message plugin will break if using JQ v9 as JQV9 does not use "browser" referenced in the plugin

如果使用 JQ v9,NB 消息插件将中断,因为 JQV9 不使用插件中引用的“浏览器”

1st step:Add the plugin code to both sending and receiving docs:

第一步:将插件代码添加到发送和接收文档中:

http://benalman.com/projects/jquery-postmessage-plugin/

http://benalman.com/projects/jquery-postmessage-plugin/

2nd step:Add this to sending doc:

第二步:将此添加到发送文档:

   $.postMessage(
$(X).html(),    
'http://DOMAIN [PORT]/FOLDER/SUBFOLDER/RECIEVINGDOCNAME.XXX'   
 )  ;      

Where X can be a local var containing preformatted json array or other stuff, and the http url here is the address of the receiving document.

其中 X 可以是包含预先格式化的 json 数组或其他内容的本地变量,这里的 http url 是接收文档的地址。

3rd step:Add this to receiving doc:

第 3 步:将此添加到接收文档中:

    $.receiveMessage(
    function(event){
        alert("event.data: "+event.data);
                $("#testresults").append('<h1>'+event.data+'<h1>');

    },          
    'http://DOMAIN.COM OR SOMETHING'

);

Where the http url is the DOMAIN of the sending document. Good in IE 8, 9, FF16, safari Windows (windows wait x V9 not tested yet), safari x mac thing.

其中 http url 是发送文档的域。在 IE 8、9、FF16、safari Windows(windows wait x V9 尚未测试)、safari x mac 方面表现良好。

The result is any item you want out of another domain page (that you have access to..).

结果是您想要从另一个域页面(您有权访问......)中的任何项目。