javascript - window.postMessage 从 iframe 到被调用者,iframe 和被调用者都在同一个域中

标签 javascript

从 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.parentwindow.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/

相关文章:

javascript - 有没有办法从一个别名下的所有索引中获得一个统一的映射?

javascript - 具有 2 个屏幕的属性 screen.width (IE)

javascript - 如何在 J.T.Sage DateBox 中禁用已选择的下一个日期框的日期

javascript - 如何显示隐藏链接中的特定部分

Javascript:随机排列表行

javascript - 单击单选按钮时未获取更改事件

javascript - 如何修复 eslint 箭头体错误中的 block 语句?

javascript - RxJS forkjoin 未运行

javascript - 如何更改单击时评级字段的颜色?

javascript - JQuery 验证数据存在于带有空格的表中