1.估计很少人知道html5 apis里有一个window.postmessage api。window.postmessage的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像是跨域的ajax,但不是浏览器跟服务器之间交互,而是在两个客户端之间通信。让我们来看一下window.postmessage是如何工作的。除了ie6、ie7之外的所有浏览器都支持这个功能。
2. 先创建一个index.html 文件。 (在测试的的时候必须用服务器测试呀 ; file:// 这样地址的开头是错误的不准许访问发送(因为window.postmessage这个方法是跨域 跟 ajax 差不多 所以很相似))
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title> <style> body,p{ margin: 0px; padding: 0px; } </style></head><body> <script> //弹出一个新窗口 var domain = 'http://localhost:8080/chenzhenhua/'; var mypopup = window.open(domain+'lister.html','mywindow');//打开另一个网址 // var array=["100","liyoubing","200"]; var array=[{"姓名":"李友冰"},{"性别":"男"}] //周期性的发送消息 setinterval(function(){ //var message = 'hello! the time is: ' + (new date().gettime()); // console.log('blog.local: sending message: ' + message); //array:发送消息de数据,domain: 是url; mypopup.postmessage(array,domain); },6000); </script></body></html>
3. 在创建 lister.html 文件 代码如下:
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title></head><body> <script> //监听消息反馈 window.addeventlistener('message',function(event) { console.log(event); if(event.origin !== 'http://localhost:8080') return; console.log('received response: ',event.data); },false); </script></body></html>
4.结果如下:
相关推荐:
javascript实现html页面之间参数传递的四种方法实
html怎样实现页面跳转时传递参数
以上就是实战演练--js实现在网页间传递数据的详细内容。