我正在开发一个Google Chrome浏览器扩展程序,该程序可以在网页上插入脚本,从网页中收集一些数据,调用iframe并将该数据发送到iframe。由于此过程需要跨域,因此实现该功能我唯一想到的就是postMessage,但是我无法在iframe中接收此数据。
(顺便说一句,还有其他方法可以实现相同的功能吗?)
下面是当用户单击扩展名时我在网页上插入的脚本。
jQuery('body').append('<div style="height: 100% !important; width: 100% !important; position: fixed !important; margin: 0% auto !important; background: rgba(17, 17, 17, 0.9) !important; left: 0 !important; right: 0 !important; z-index: 99999999 !important; top: 0% !important;" id="image-grabber-container"><iframe id="vwframe" src="https://example.com/abcd.php" frameborder="0" style="display: block !important; position: fixed !important; height: 100% !important; width: 100% !important; top: 0px !important; left: 0px !important; bottom: 0px !important; right: 0px !important; margin: 0px !important; clip: auto !important; z-index: 7147483657 !important;"></iframe></div>');
setTimeout(function(){
var dTitle = document.title;
var receiver = document.getElementById('vwframe').contentWindow;
receiver.postMessage(dTitle, '*');
},1000);
我在setTimeout
这里使用过的只是为了确保在发布消息时iframe可用/已加载。
现在,我在iframe中调用一个脚本来接收消息:
window.onload = function() {
function receiveMessage1(e) {
console.log('mSG');
if (e.origin !== currentUrl)
return;
parentTitle = e.data;
console.log(parentTitle);
}
if (window.addEventListener){
console.log('if');
window.addEventListener("message", receiveMessage1, false);
console.log('if end');
} else {
console.log('else');
attachEvent("onmessage", receiveMessage1);
console.log('else end');
}
}
我在控制台中没有看到任何错误,但是receiveMessage1
功能无法正常工作。这可能是什么原因?
PS我能够将消息从iframe发送到父级,反之亦然。
尝试不使用setTimeout和window.onload,而是这样:
<script>
function receiveMessage1(e) {
console.log('mSG');
if (e.origin !== currentUrl)
return;
parentTitle = e.data;
console.log(parentTitle);
}
if (window.addEventListener){
console.log('if');
window.addEventListener("message", receiveMessage1, false);
console.log('if end');
} else {
console.log('else');
attachEvent("onmessage", receiveMessage1);
console.log('else end');
}
</script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句