<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>cross-domain</title>
</head>
<body>
<h3>this page from :<span id="host"></span></h3>
<input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>
<ul>
<li>firefox、chrome等高级浏览器采用html5 postMessage方法</li>
<li>IE6 7等使用window.name方法</li>
<li>支持双向跨域,在chrome 13、firefox6、IE6+测试通过</li>
<li>window.name可以通过data加随机数方式,避免两次提交的数据相同,本例没做处理,所以如果不改变value值点击提交是不会触发alert的</li>
</ul>
<script type="text/javascript">
document.getElementById('host').innerHTML = location.host;
function send(){
var val = document.getElementById('data').value;
sendMessage(val);
}
(function(win, doc){
var ifr = win.parent;
var cb = function(json){
alert(location.host+" get msg:"+json);
};
var sendMessage = function(){
if(win.postMessage){
if (win.addEventListener) {
win.addEventListener("message",function(e){
cb.call(win,e.data);
},false);
}else if(win.attachEvent) {
win.attachEvent("onmessage",function(e){
cb.call(win,e.data);
});
}
return function(data){
ifr.postMessage(data,'*');
};
}else{
var hash = '';
setInterval(function(){
if(win.name!==hash){
hash = win.name;
cb.call(win,hash);
}
},50);
return function(data){
ifr.name = data;
};
}
}
win.sendMessage = sendMessage();
})(window, document);
</script>
</body>
</html>
没有评论:
发表评论