关于IE8浏览器的window.postMessage跨域问题整理
window.postMessage的api地址(https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage).
api里或者其他的地方对非IE浏览器都有详细的讲解,但对IE8不多,主要是IE8\9不支持addEventListener方法导致了与其他浏览器不同,项目里遇到了这个问题整理个demo:
父页面:
<!DOCTYPE html>
<html>
<head>
<title>Post Message</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
<div id="color">Frame Color</div>
</div>
<!-- <div>
<iframe id="child" src="http://localhost:8080/child/22.html"></iframe>
</div> -->
<input type="button" value="动态加载iframe" id="qqq" "load()">
<input type="button" value="ֵ向子页面传值" id="qqq2" "load2()">
<div style="display:none;" id="closeMapDiv" style="z-index:0;">
</div>
<div id="dataMap" style="display:none;">
</div>
<script type="text/javascript">
function load(){
//动态加载iframe
document.getElementById("dataMap").innerHTML = "";
document.getElementById("dataMap").style.display="";
document.getElementById("dataMap").style.height="100px";
document.getElementById("dataMap").style.width="300px";
document.getElementById("dataMap").style.zIndex=999;
var insertText = "<iframe src= http://localhost:8080/child/child.html scrolling='no' frameborder='0' style='height:100px; width:200px;'></iframe>";
document.getElementById("dataMap").innerHTML=document.getElementById("dataMap").innerHTML+insertText;
// window.frames[0].postMessage('hello','http://localhost:8080/child/22.jsp');
}
function load2(){
window.frames[0].postMessage('helloworld','http://localhost:8080/child/child.html');
}
window.attachEvent('onmessage',function(e){
var color=e.data;
alert("子页面传值:"+color);
$("#color").text(color);
// document.getElementById('color').style.backgroundColor=color;
},false);
</script>
</body>
</html>
子页面:
<!doctype html>
<html>
<head>
<style type="text/css">
html,body{
height:100%;
margin:0px;
}
</style>
</head>
<body style="height:100%;">
<div id="container" "changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
父页面传值后点我
</div>
<script type="text/javascript">
var container=document.getElementById('container');
var event;
window.attachEvent('onmessage',function(e){
event=e.origin;
alert("父页面传值:"+e.data);
if(e.source!=window.parent) return;
window.parent.postMessage('你好',e.origin);
},false);
function changeColor () {
window.parent.postMessage('我是子页面参数',event);
}
</script>
</body>
</html>