的index.html
<html>
<head>
</head>
<body>
<iframe id="iframe" src="inner.html"></iframe>
<iframe id="iframe2">
<html>
<head>
</head>
<body>
<input type="text" id="val"/>
<input type="button" id="button" onclick="callPostMessage();" />
<p><b>Main Window </b></p>
<label id="label"></label>
</body>
</html>
</iframe>
<script>
var script = document.createElement('script');
script.src = "myjs.js";
script.type = "text/javascript";
document.getElementById('iframe2').contentWindow.document.getElementsByTagName('head')[0].appendChild(script);
</script>
</body>
</html>
frame1.html
<html>
<head>
<script>
window.onload = function () {
initilizeMarsEventListener();
};
function initilizeMarsEventListener() {
console.log('In initilizeMarsEventListener');
if (window.addEventListener) {
window.addEventListener("message", receiveDataFromXYZDomain, false);
}
else {
window.attachEvent("onmessage", receiveDataFromXYZDomain);
}
}
function receiveDataFromXYZDomain(evt) {
var val = document.getElementById("label");
val.innerHTML = evt.data;
}
function sendAuthTokenToCRMDomain() {
console.log('In sendAuthTokenToXYZDomain' );
top.window.postMessage(val.value, "*");
}
</script>
</head>
<body>
<p><b>Iframe </b></p>
<input type="text" id="val" />
<input type="button" id="button" onclick="sendAuthTokenToXYZDomain();" />
<label id="label"></label>
</body>
</html>
myjs.js
window.addEventListener("message",
function (e) {
//if (e.origin !== 'http://localhost:2345') { alert("Wrong origin " + e.origin); return; }
//alert("Value from Iframe" + e.data);
var val = document.getElementById("label");
alert(e.data);
val.innerHTML = e.data;
},
false);
function callPostMessage() {
debugger;
//var val = document.getElementById("val");
val = { name : "alex"};
var iframeWin = window.parent.document.getElementById("iframe");
var iframeContent = iframeWin.contentWindow;
window.setTimeout(function() {
iframeContent.postMessage(val, "*");
}, 0);
}
(function (){
var myButton = document.createElement('button');
myButton.setAttribute("text","callPostMessage");
myButton.setAttribute("onclick","callPostMessage()");
window.parent.document.getElementById("iframe2").contentWindow.document.getElementsByTagName('body')[0].appendChild(myButton);
})("addControl", window);
单击第2帧中的按钮postmessage方法被调用并由receiveDataFromXYZDomain中的第1帧接收。然而,evt.origin出现了关于:&#34;关于:&#34;在ie / edge(在chrome / firefox中正常工作)。