网页浏览总次数
2011年12月20日星期二
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>HTML5</title> </head> <script type="text/javascript" src="http://achau.appspot.com/js_/util.js%22%3E%3C/script> <script type="text/javascript"> var url1 = 'http://achau.appspot.com/demo/html5/crossdoc/iframe1.html'; var url2 = 'http://austinchau.googlecode.com/svn/trunk/demo/html5/crossdoc/iframe2.html'; var iframeWidth = 300; var iframeHeight = 200; var frameborder = 1; window.onload = function() { // check if HTML5 cross document 'postMessage' is supported if (typeof window.postMessage == 'undefined') { var div = document.createElement('div'); div.innerHTML = 'Sorry your browser does not support the ' + '<a href="http://www.whatwg.org/specs/web-apps/current-work/#crossDocumentMessages">HTML5 Cross-Document Messaging.</a>' + '<br>Please use Firefox 3 or IE8.'; document.body.innerHTML = ''; document.body.appendChild(div); return; } buildIframes(); }; function buildIframes() { var iframe1 = document.createElement('iframe'); iframe1.src = url1; iframe1.width = iframeWidth; iframe1.height = iframeHeight; iframe1.frameborder = frameborder; iframe1.style.border = 'solid black 1px;'; var iframe2 = document.createElement('iframe'); iframe2.src = url2; iframe2.width = iframeWidth; iframe2.height = iframeHeight; iframe2.frameborder = frameborder; iframe2.style.border = 'solid black 1px;'; document.body.appendChild(iframe1); document.body.appendChild(iframe2); } </script> <style> body { font-size: 12px; color: gray; } </style> <body> This sample demonstrates two iframes of different domains passing their respective mouse coordinates to each other using <a href="http://www.whatwg.org/specs/web-apps/current-work/#crossDocumentMessages">HTML5 Cross-Document Messaging.</a> <br><br> [ <a href='http://code.google.com/p/austinchau/source/browse/#svn/trunk/demo/html5/crossdoc'>Source code</a> ] <br><br> * Move your mouse over the two iframes <br><br> </body> </html>
iframe2.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Untitled</title> </head> <style> body { font-size: 12px; color: gray; } </style> <script type="text/javascript"> window.onload = function() { document.getElementById('title').innerHTML = 'Domain: ' + document.location.host; window.document.onmousemove = function(e) { var x = (window.Event) ? e.pageX : window.event.clientX; var y = (window.Event) ? e.pageY : window.event.clientY; window.parent.frames[0].postMessage('x = ' + x + ' y = ' + y, '*'); }; var onmessage = function(e) { var data = e.data; var origin = e.origin; document.getElementById('display').innerHTML = data; }; if (typeof window.addEventListener != 'undefined') { window.addEventListener('message', onmessage, false); } else if (typeof window.attachEvent != 'undefined') { window.attachEvent('onmessage', onmessage); } }; </script> <body> <div id="title"></div> <br> <div id="display"></div> </body> </html>
iframe1.html
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> |
| <html> |
| <head> |
| <title>Untitled</title> |
| </head> |
| <style> |
| body { |
| font-size: 12px; |
| color: gray; |
| } |
| </style> |
| <script type="text/javascript"> |
| window.onload = function() { |
| document.getElementById('title').innerHTML = 'Domain: ' + document.location.host; |
| window.document.onmousemove = function(e) { |
| var x = (window.Event) ? e.pageX : window.event.clientX; |
| var y = (window.Event) ? e.pageY : window.event.clientY; |
| window.parent.frames[1].postMessage('x = ' + x + ' y = ' + y, '*'); |
| }; |
| var onmessage = function(e) { |
| var data = e.data; |
| var origin = e.origin; |
| document.getElementById('display').innerHTML = data; |
| }; |
| if (typeof window.addEventListener != 'undefined') { |
| window.addEventListener('message', onmessage, false); |
| } else if (typeof window.attachEvent != 'undefined') { |
| window.attachEvent('onmessage', onmessage); |
| } |
| }; |
| </script> |
| <body> |
| <div id="title"></div> |
| <br> |
| <div id="display"></div> |
| </body> |
| </html> |
HTML5:使用postMessage实现Ajax跨域请求
由于同源策略的限制,Javascript存在跨域通信的问题,典型的跨域问题有iframe与父级的通信等。
常规的几种解决方法:
(1) document.domain+iframe; (2) 动态创建script; (3) iframe+location.hash; (4) flash。
这里不细说这几种方法,记录的是HTML5的window.postMessage。postMessage兼容IE8+、Firefox、Opera、Safari、Chrome。
需要两个异域的服务器来做测试,当然也可以用本地和线上服务器作为两个异域的服务器。假如使用phonegap开发,就可以将请求文件安装在客户端,然后动态请求服务器的数据处理,获得并显示数据。这样就可以用任意Web开发语言及方法来开发phonegap App所需的后台。
1. postMessage的用法
postMessage是HTML5为解决js跨域问题而引入的新的API,允许多个iframe/window跨域通信。假设有结构如下:
test.html<section id="wrapper"> <header> <h1>postMessage (跨域)</h1> </header> <article> <form> <p> <label for="message">给iframe发一个信息:</label> <input type="text" name="message" value="son" id="message" /> <input type="submit" /> </p> </form> <h4>目标iframe传来的信息:</h4> <p id="test">暂无信息</p> <iframe id="iframe" src="http://xiebiji.com/works/postmessage/iframe.html"></iframe> </article> </section>
iframe.html<strong>iframe指向xiebiji.com</strong> <form> <p> <label for="message">给父窗口发个信息:</label> <input type="text" name="message" value="dad" id="message" /> <input type="submit" /> </p> </form> <p id="test">暂无信息。</p> 下面是test.html里的Javascript代码(发送数据): var win = document.getElementById("iframe").contentWindow; document.querySelector('form').onsubmit=function(e){ win.postMessage(document.getElementById("message").value,"*"); if (e.preventDefault) e.preventDefault(); e.returnValue = false; }
win.postMessage(document.getElementById("message").value,"*");
然后是iframe.html里侦听接收数据的代码:
var parentwin = window.parent; window.onmessage=function(e){ document.getElementById("test").innerHTML = e.origin + "say:" + e.data; parentwin.postMessage('HI!你给我发了"<span>'+e.data+'"</span>。',"*"); };
然后iframe.html也给test.html发送回应的数据,test.html接收数据。代码雷同,就不贴代码了。
点此查看Demo(代码素Joe哥给的)
2. Ajax跨域请求
基于以上的跨域通信,只要将Ajax代码放在iframe.html里的onmessage处理函数里头,将test.html用postMessage传过来的数据作为参数发送请求,再将返回的数据用postMessage传给test.html。这样就实现了跨域的Ajax请求。其实是很简单的东西。贴个示例代码吧,但跟以上的代码无关。
(function(){
//获取跨域数据
window.onmessage = function(e){
var url = "http://yangzebo.com/demo/noforget/test.php?msg=" + e.data;
//Ajax
var xhr = getXHR();
if(xhr){
xhr.open("GET",url,true);
xhr.onreadystatechange = changeHandle;
xhr.send(null);
}else{
alert("不支持Ajax");
}
function changeHandle(){//返回处理
if(xhr.readyState == 4){
var parentwin = window.parent;
parentwin.postMessage(xhr.responseText,"*");//跨域发送数据
}
}
function getXHR(){//获取XMLHttpRequest
var xhr_temp;
if(window.XMLHttpRequest){
xhr_temp = new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr_temp = new ActiveXObject("Microsoft.XMLHTTP");
}else{
xhr_temp = null;
}
return xhr_temp;
}
};
})();
有兴趣代码请求啥的自个用开发人员工具看吧,“zebo男”是从数据库读出来的,“my msg”是sendAndReceive.html发给test.php的Ajax请求的参数,通过test.php和iframeforAjax.html回传到sendAndReceive.html。
3. 提示
要获取iframe的contentWindow才能调用postMessage。postMessage一定要在iframe加载完成之后调用才可以正常运行。(这个耗了我好长时间)
最后要感谢Joe哥的提示和给我偷用服务器来测试的hulin小妹妹。:D
[原帖]:http://yangzebo.com/blog/?p=208
Xdomain
<!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>
<div style="width:100%;border:1px solid green;">
<h3>this page from :<span id="host"></span></h3>
<input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>
</div>
<iframe id="iframeA" src="http://example.cn/client.html" style="border:1px solid #ff6600;width:100%;height:300px;"></iframe>
<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 = doc.getElementById('iframeA').contentWindow;
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>
<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>
<div style="width:100%;border:1px solid green;">
<h3>this page from :<span id="host"></span></h3>
<input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>
</div>
<iframe id="iframeA" src="http://example.cn/client.html" style="border:1px solid #ff6600;width:100%;height:300px;"></iframe>
<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 = doc.getElementById('iframeA').contentWindow;
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>
クライアント
<!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>
<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>
(转)HTML5之window.postMessage实现跨域传递消息
今天在了解HTML5的新特性中,发现利用window.postMessage来实现跨域方面的操作真的是很方便,故把学习的心得记录下来,方便在以后的项目中遇到能够顺利解决.
首先建立两个文件
(1)在http://h.com/Html/目录下创建window_postMessage.htm文件,该文件代码如下:
<!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">
<head>
<title></title>
</head>
<body>
<pre>
(1)利用window.postMessage()跨域传递消息
(2)本域是http://h.com,向http://x.com/Html/webtwo.htm 传递数据
<button id="btnPassData"> 跨域传递消息</button>
</pre>
<div> //利用Iframe加载另一个域http://x.com/下的文件
<iframe src="http://x.com/Html/webtwo.htm" id="twoiframe" width="800" height="200">
</iframe>
</div>
</body>
</html>
<script type="text/javascript">
window.onload = function() {
document.getElementById("btnPassData").onclick = function() {
var iframedom = document.getElementById("twoiframe").contentWindow;
if (typeof window.postMessage !== "undefined") {
iframedom.postMessage("Hellow,这个消息来源于http://h.com", "http://x.com");
//iframe向http://x.com/Html/webtwo.htm传递字符串消息,在下面蓝色部分看webtwo.htm如何接收传递过来的数据
}
}
if (window.attachEvent) {
window.attachEvent("onmessage", receiveMsg);
}
else {
window.addEventListener("message", receiveMsg, true);
}
};
var receiveMsg = function(e) {
document.title = e.origin; //获取跨域传的源
alert(e.data); //获取传递过来的数据
}
</script>
(2)http://x.com/Html/webtwo.htm下webtwo.htm页面的代码如下
<!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">
<head>
<title>第二个网站</title>
</head>
<body>
<div id="testdiv" style="border: 1px solid lime; width: 400px; height: 400px;">
UserName:<input type="text" id="txtUser" value="jackie" />
<br />
Password:<input type="text" id="txtPwd" value="123" />
</div>
<br />
接受来自http://h.com域下传递过来的值
<div id="acc" style="border: 1px solid blue; width: 100px; height: 100px;">
</div>
</body>
</html>
<script type="text/javascript">
window.onload = function() {
if (window.attachEvent) {
window.attachEvent("onmessage", acceptMsg);
}
else {
window.addEventListener("message", acceptMsg, true);
}
}
var acceptMsg = function(e) { //该函数用来表示在window.onmessage事件触发时进行接收数据的处理
if(e.origin.indexOf("http://h.com")){ //这句的作用是排除其他非法的域名,也就是说只接收http://h.com传递过来的数据
alert(e.data) ;//webtwo.html页面接收数据
}
window.top.postMessage("Got it Thanks", "http://h.com/Html/window_postMessage.htm"); //向页面回传数据,那么在
};
</script>
总结:
(1)利用window.postMessage进行跨域传递数据时.在window.onload事件中,如果通过闭包的形式来帮顶事件接收acceptMsg 函数是不行的。
(2)window.postMessage作为HTML5的新特性,在IE8,FF3.5+,chrome,opera,safari中才支持,IE较低的版本是不支持的.
(3)window.postMessage不仅可以用在跨域传递数据,在同源策略中也可以使用.
(4) 在利用window.postMessage进行跨域传递数据时,可以利用Event.origin属性来过滤那些不合法的域名来传递数据,
订阅:
博文 (Atom)