有没有办法在Javascript中收听传出的postMessages?

时间:2015-06-22 11:14:04

标签: javascript event-listener postmessage

有没有办法在原始页面上监听postMessages?
当前窗口对象发送postMessage时被触发的任何事件?

我搜索了很多,但没有找到任何东西。

非常感谢您的帮助。谢谢!

[编辑]我试图这样做的原因是因为我正在开发一个分析页面通信的扩展。例如,页面如何与内部IFrame或它打开的新窗口进行通信。 到目前为止我所做的是将Javascript-File注入每个IFrame / new Window,并为窗口对象添加一个消息监听器。有了这个,我可以检测到目标收到消息的时间。 问题是我想获得源的完整URL,如果它是跨源的,这是不可能的。

2 个答案:

答案 0 :(得分:2)

猴子修补可以解决问题:

const pm = window.postMessage;
window.postMessage = (msg, domain) => {
    console.log(msg);
    pm(msg, domain);
}

答案 1 :(得分:0)

您可以在函数中包装window.postMessage()并在那里触发一个自定义事件(使用JS,jQuery或您喜欢的其他库中的本机自定义事件)。

使用custom event下的示例(适用于Chrome和Firefox)。 请查看控制台选项卡。

http://jsbin.com/liweyobazi/edit?html,output

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Test</title>

    <script>

        window.app = {
            start: function () {
                // get the iframe
                var domain = '*';
                var iframe = document.getElementById('myIFrame').contentWindow;

                // listen to custom event
                document.body.addEventListener('postMessage', function (e) {
                    console.log('postMessage has been listened');
                }, false);


                function myPostMessage(message, domain) {
                    iframe.postMessage(message, domain); //send the message and target URI
                    // creat a custom event
                    var event = new Event('postMessage');
                    document.body.dispatchEvent(event);
                }

                // send preioducally messages for example
                setInterval(function () {
                    var message = 'Time is: ' + (new Date().getTime());
                    myPostMessage(message, domain); //send the message and target URI
                }, 1000);
            }
        };

    </script>

</head>

<body onload="window.app.start();">
    <iframe id="myIFrame" src="http://www.w3schools.com"></iframe>
</body>
</html>

这里有一个小修改版本,允许将自定义函数传递给postMessage的原始事件。

http://jsbin.com/liweyobazi/1/edit?html,console,output

在你的问题上的最后一次编辑之后。 只有当你拥有&#34; destination&#34;这个解决方案才有效。源代码,可能不适用于您的特定场景(我仍然希望它对其他读者也有用)。

相关问题