跨站点脚本编写iframe权限被拒绝的问题

时间:2013-02-23 18:55:08

标签: javascript html wordpress iframe cross-domain

我在以下代码中收到Cross Site Scripting错误。

的Javascript

 function resizeIframe(ifRef) 
            {
                var ifDoc;
                //alert(ifRef);

                try
                { 
                    ifDoc = ifRef.contentWindow.document.documentElement; 
                }
                catch( e )
                {
                   alert(e);
                    try
                    { 
                    ifDoc = ifRef.contentDocument.documentElement; 
                    }
                    catch( ee ){
                             alert(ee);
                          } 
                }
                //var doc = ifRef.height;
                //alert(doc);
                if(ifDoc)
                {
                    ifRef.height = 1; 
                    ifRef.style.height = ifDoc.scrollHeight+'px';               
                }
            }

I帧

<iframe onload="resizeIframe(this)" style="margin-bottom: 16px;" src="ourteamnav/first.php" frameborder="0" scrolling="no" width="597" height="240"></iframe>

错误正在跟随

对于'e':

Mozilla Firefox:错误:访问属性'文档'的权限被拒绝

Google Chrome: TypeError:无法读取未定义的属性'documentElement'

Internet Explorer: TypeError:权限被拒绝

对于'ee':

Mozilla Firefox:错误:访问属性'documentElement'的权限被拒绝

Google Chrome: TypeError:无法读取属性'documentElement'为null

Internet Explorer:错误:访问被拒绝。

我认为由于域名指向另一个域而无法通过一般方式解决。因此,任何人都可以指导我解决此问题,而无需使用Javascript contentDocument.documentElementcontentWindow.document.documentElement的这些属性来根据内部内容动态调整Iframe内容的大小。

由于

2 个答案:

答案 0 :(得分:3)

Christophe的答案外,我还想指出(遗憾的是)postMessage并不适用于所有浏览器。

幸运的是,Josh Fraser已提供a backwards compatible version of window.postMessage()。它检查浏览器是否支持postMessage - 方法。如果是的话,就会使用它。如果没有,它会使用网址(来自iframe和父级)来传递数据。

现在你可以使用以下方法让两个窗口和#34;谈话&#34;彼此:

XD.postMessage(msg, src, frames[0]);
XD.receiveMessage(function(message){
    window.alert(message.data + " received on "+window.location.host);
}, 'URL');

请确保正确阅读文档,因为必须正确设置配置。

答案 1 :(得分:2)

正如您所说,这是一个跨域问题。

如果您对两个页面都有控制权,则可以使用postMessage在两个页面之间交换信息。

一些参考文献:

相关问题