Javascript postMessage不';不要在油腻的环境中工作
因为它不能访问跨域iframe上的contentWindow属性,但在纯Firefox中它可以工作。以下是隔离此问题的一系列代码:Javascript postMessage不';不要在油腻的环境中工作,javascript,firefox,greasemonkey,same-origin-policy,Javascript,Firefox,Greasemonkey,Same Origin Policy,因为它不能访问跨域iframe上的contentWindow属性,但在纯Firefox中它可以工作。以下是隔离此问题的一系列代码: 在本地服务器上创建3个文件: test.html <SCRIPT language="JavaScript" SRC="http://localhost/postmsg.js"></SCRIPT> <iframe src="http://127.0.0.1/iframe.htm" id="iframe"></iframe&g
<SCRIPT language="JavaScript" SRC="http://localhost/postmsg.js"></SCRIPT>
<iframe src="http://127.0.0.1/iframe.htm" id="iframe"></iframe>
<div>Click anywhere on this page to see message from embedded iframe,
which do not need to be on the same domain</div>
此js文件可以作为标准包含文件html工作,然后忽略第一个注释,但在重命名扩展名为user.js后,可以将其安装在greasemonkey中,然后在调用contentWindow时在第行之后停止工作
请注意,即使js解释器的主html和框架html位于同一服务器上,这些文件也位于不同的域上,因为js解释器不知道localhost和127.0.0.1是相同的
我放了“@include*”,这样你就可以在不同的网站上查看它,看起来这个错误只存在于跨域iFrame上。如果你去translate.google.com,它有几个iFrame,但都在同一个域中,这个脚本可以正常工作
问题是,greasemonkey上到底在进行什么跨域安全检查?这与此工具的使用相矛盾。恶意网站无法安装脚本,用户必须同意。我在这个问题上被困了很长时间,因为firebug并没有指出它在跨域iframe上显示的属性实际上在浏览器的js引擎上不可用。错误消息是什么?有一些,;丢失没有错误消息,这是错误的一部分。该函数只是不执行。(分号在JS中是可选的?)
<SCRIPT language="JavaScript" SRC="http://127.0.0.1/postmsg.js"></SCRIPT>
<div id="message"></div>
// ==UserScript==
// @include *
// ==/UserScript==
alert('script loaded')
window.addEventListener('click',
function() {
frame = document.getElementsByTagName("iframe")[0]
cwindow = frame.contentWindow //here comes the error anything after this line won't execute in greasemonkey
alert("this won't show in greasemonkey");
cwindow.postMessage("hello, iframe!","*")
},
true);
window.addEventListener("message", function(e){
alert("message from iframe: main window was clicked! " +e.data);
document.getElementById('message').textContent += "message from iframe: main window was clicked!\n"
}, true);