从 iframe 向被调用方使用 window.postMessage 时出现问题。 iframe 和被调用方都在同一个域中。
callee -- 第一个注册的监听器,监听消息。 在 calle 处使用 Marionette.js,下面是在 callee 处的代码
return Marionette.ItemView.extend({
initialize: function(opts){
window.addEventListener('message', this.listenToMessage);
},
// 'listenToMessage' never gets called
listenToMessage: function(message){
console.log('message received from iframe');
}
});
});
从 iframe 发布消息的代码。确保 window.postMessage 成功,因为它不会进入 window.onerror,但消息不会被接收,下面是 iframe onload 中的代码
<script>
window.onload = function() {
var origin = document.location.origin; //-->https://dev03.com
console.log('About to post message ---> ' origin: '+origin);
window.postMessage('Hi this message is from iFrame', origin);
};
window.onerror = function(message, source, lineno, colno) {
console.log('message --> '+message);
console.log('source --> '+source);
console.log('lineno --> '+lineno);
console.log('colno --> '+colno);
}
</script>
最佳答案
根据MDN documentation应该在目标窗口上调用 postMessage 函数。在您的代码中,您将在 iframe 的窗口中调用它。尝试以下操作,看看是否可行。我还没有测试过它,但从我读到的内容来看应该是这样。
<script>
window.onload = function() {
var origin = document.location.origin; //-->https://dev03.com
console.log('About to post message ---> ' origin: '+origin);
var targetWindow = window.opener; //added this
targetWindow.postMessage('Hi this message is from iFrame', origin);//changed target
};
window.onerror = function(message, source, lineno, colno) {
console.log('message --> '+message);
console.log('source --> '+source);
console.log('lineno --> '+lineno);
console.log('colno --> '+colno);
}
</script>
编辑
我想 window.opener
属性取决于被调用的 window.open()
? IDK。无论哪种情况,window.parent
或 window.top
都应该适用于您的用例(我这次测试过)。
var targetWindow = window.parent; //added this
targetWindow.postMessage('Hi this message is from iFrame',origin);//changed target
关于javascript - window.postMessage 从 iframe 到被调用者,iframe 和被调用者都在同一个域中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520334/