有没有办法在原始页面上监听postMessages?当前窗口对象正在发送postMessage时触发的任何事件?
我搜索了很多,但没有真正找到任何东西。
非常感谢您的帮助。谢谢!
[[Edit]]之所以要这样做,是因为我正在开发扩展程序以分析页面的通信。例如,页面如何与内部IFrame或打开的新窗口进行通信。到目前为止,我所做的就是将JavaScript文件注入到每个IFrame /新窗口中,并向该窗口对象添加消息侦听器。有了这个,我可以检测到何时在目标上收到了一条消息。问题是我想获取源的完整URL,如果它是跨源的,则不可能。
您可以将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
在您问题的最后编辑之后。仅当您拥有“目标”源代码并且可能不适用于您的特定情况时,该解决方案才明显有效(仍然希望它对其他读者也有用)。
猴子修补可以解决问题:
const pm = window.postMessage;
window.postMessage = (msg, domain) => {
console.log(msg);
pm(msg, domain);
}