gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:41:19 26 4
gpt4 key购买 nike

大家好,我遇到了跨域问题。

我有 1 台服务器 (example.com),其中:

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

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

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

所以在 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 资源位于不同的域中。

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

最佳答案

现代浏览器根本不允许这样做。首选技术是使用 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
}

关于javascript - 尝试从 iframe 内部调用 js 函数到其父级的跨域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12607072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com