Javascript iframe父窗口(window.top/window.parent)上的调用函数(规避跨原点对象访问安全)

Javascript iframe父窗口(window.top/window.parent)上的调用函数(规避跨原点对象访问安全),javascript,iframe,cross-domain,postmessage,Javascript,Iframe,Cross Domain,Postmessage,当页面(域B)上的iframe(域a)尝试访问窗口的属性时,是否有办法避免出现跨源安全错误。top 我想在域B的上下文中,通过域a的iframe中的事件调用属于域B的函数,即someFunc 例如: a.com/index.html var someFunc=t=>document.querySelector(“#test”).text=t; 这是一些虚拟文本。 b.com/index.html 试验 document.querySelector(“#btn”).addEventListe

当页面(域B)上的iframe(域a)尝试访问
窗口的属性时,是否有办法避免出现跨源安全错误。top

我想在域B的上下文中,通过域a的iframe中的事件调用属于域B的函数,即
someFunc

例如:

a.com/index.html


var someFunc=t=>document.querySelector(“#test”).text=t;
这是一些虚拟文本。
b.com/index.html


试验
document.querySelector(“#btn”).addEventListener(“单击”,(e)=>{
window.top.someFunc(“此文本已通过交叉原点更改”)
});
此示例在Firefox上引发以下错误:

SecurityError:cross-origin object上访问属性“someFunc”的权限被拒绝

规避此问题的正确方法是使用-本质上,从iframe向上发送一条消息到其父窗口,如果它有
“message”
的事件侦听器,则可以相应地做出反应

即:

a.com/index.html


让someFunc=t=>document.querySelector(“#test”).text=t;
addEventListener(“message”,event=>someFunc(e.data));
这是一些虚拟文本。
b.com/index.html


试验
文档查询选择器(“btn”)
.addEventListener(“单击”,事件=>{
window.parent.postMessage(“已更改的文本”http://a.com");
});

no…………这是您需要使用postMessage并在两个域上都有代码的地方。我知道这看起来一定很傻,但我很感激您的回答,因为否则我可能找不到postMessage。。。我马上写答案