尝试从内部iframe调用js函数到它的父级的跨域问题

时间:2012-09-26 17:18:46

标签: javascript cross-domain

大家好我都有跨域问题。

我有一台服务器(example.com),我有:

index.html作为主页,indexIFrame.html作为index.xhtml内的框架

Index.html从静态服务器加载大量javascript文件(例如staticServer:8090 / myScript.js)

另外indexIFrame.html从另一个静态服务器加载它自己的javascript文件(anotherServer:8070 / myOtherScript.js)

所以在myOtherScript.js中,我这样做:

parent.MyMainClass.showPopup();

MyMainClass类在staticServer的js文件中声明(这些文件可用于index.xhtml)

当我运行代码时,我得到了:

Unsafe JavaScript attempt to access frame with URL http://example:8080/myapp/myList.xhtml from frame with URL http://example:8080/myapp/myListIFrame.xhtml Domains, protocols and ports must match.

myList和myListIframe它们位于同一服务器中,只有javascript资源位于不同的域中。

所以我不确定如何使这项工作。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

现代浏览器根本不允许这样做。首选技术是使用https://developer.mozilla.org/en-US/docs/DOM/window.postMessage代替。

...但是像往常一样,你会发现IE处于自己的小世界并且不支持该标准。我知道有一些框架提供了跨浏览器解决方案,但我不能特别推荐其中任何一种。

这是一个跨浏览器的监听器:

if (typeof(window.postMessage) != 'undefined') {
    if (typeof(window.addEventListener) != 'undefined') {
        window.addEventListener("message", function(event) {
            doSomething(event.data);
        }, false);
    } else {
        window.attachEvent('onmessage', function(e) {
            doSomething(e.data);
        });
    }
}​

......和发件人......

if (typeof(window.postMessage) != 'undefined') {
    //modern browsers...
    window.top.postMessage('my data', '*');
} else {
    //older browsers - just access window.top
}

答案 1 :(得分:0)

尝试在服务器上创建一些别名。

例如:http://example:8080/myapp/myScript.js会导致staticServer:8090/myScript.js,依此类推。

这可能会欺骗javascript,因为它应该认为这些JS文件确实在你的服务器上。