window.postMessage实现网页间通信

window.postMessage() 方法可以安全地实现跨域通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机 (两个页面的模数 Document.domain设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

一、安装live-server

要想实现跨窗口通信,必须要在服务器上运行,直接用浏览器打开HTML文件只能处理单个文件,窗口之间无法通信。

npm install -g live-server
    
    

使用命令live-server进行启动。

安装live-server,在任意位置启动服务器。

在服务器中启动之后,会看见文档中多了一个script标签。这段代码是由live-server插入的。当运行在后台的live-server检测到文件变化,就会通过websockt向网页发送“reload”消息,从而可以实现浏览器中的网页总是实时的响应文件的变更。


    
    
  1. // <![CDATA[ <-- For SVG support
  2. if ( 'WebSocket' in window) {
  3. ( function() {
  4. function refreshCSS() {
  5. var sheets = [].slice.call( document.getElementsByTagName( "link"));
  6. var head = document.getElementsByTagName( "head")[ 0];
  7. for ( var i = 0; i < sheets.length; ++i) {
  8. var elem = sheets[i];
  9. head.removeChild(elem);
  10. var rel = elem.rel;
  11. if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
  12. var url = elem.href.replace( /(&|\?)_cacheOverride=\d+/, '');
  13. elem.href = url + (url.indexOf( '?') >= 0 ? '&' : '?') + '_cacheOverride=' + ( new Date().valueOf());
  14. }
  15. head.appendChild(elem);
  16. }
  17. }
  18. var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
  19. var address = protocol + window.location.host + window.location.pathname + '/ws';
  20. var socket = new WebSocket(address);
  21. socket.onmessage = function(msg) {
  22. if (msg.data == 'reload') window.location.reload();
  23. else if (msg.data == 'refreshcss') refreshCSS();
  24. };
  25. console.log( 'Live reload enabled.');
  26. })();
  27. }
  28. // ]]>

二、基础知识

MessageEvent有以下几个属性:

  • data:从其他window中传递过来的对象
  • origin:调用 postMessage 时消息发送方窗口的 origin
  • source:对发送消息的窗口对象的引用; 您可以使用此来在具有不同origin的两个窗口之间建立双向通信。

在发送数据窗口执行:otherWindow.postMessage(msg,origin)

  • otherWindow:表示接受数据的窗口的window对象,包括iframe的子窗口和通过window.open打开的新窗口。
  • msg表示要发送的数据,包扩字符串和对象(ie9以下不支持,可以利用字符串和json互换)。
  • origin表示接收的域名。

三、最简单的一个demo

父窗口打开一个子窗口,然后询问子窗口:“吃饭了吗”,子窗口回复父窗口:“吃了”
father.html


    
    
  1. <html>
  2. <body>
  3. </body>
  4. <script>
  5. window.addEventListener("message", function(e) {
  6. document.querySelector("body").appendChild(document.createTextNode('son say: ' + e.data))
  7. })
  8. var son = window.open("son.html")
  9. son.onload = function() {//必须得要等到儿子加载完成才可以说话
  10. son.postMessage("吃饭了吗", location.href)
  11. }
  12. </script>
  13. </html>

son.html


    
    
  1. <html>
  2. <body>
  3. </body>
  4. <script>
  5. window.addEventListener("message", function() {
  6. console.log(event)
  7. document.querySelector("body").appendChild(document.createTextNode("father say: " + event.data))
  8. event.source.postMessage("吃了", event.origin)
  9. })
  10. </script>
  11. </html>

四、一个网页聊天系统

father.html


    
    
  1. <html>
  2. <head>
  3. <style>
  4. textarea,
  5. input {
  6. width: 80%;
  7. font-size: 20px;
  8. font-family: "Consolas";
  9. }
  10. textarea {
  11. height: 80%;
  12. }
  13. input {
  14. height: 10%;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div style="text-align:center">
  20. <textarea readonly></textarea>
  21. <input type="text" style="margin-top:10px" onkeydown="keydown()">
  22. </div>
  23. </body>
  24. <script>
  25. function $(sel) {
  26. return document.querySelector(sel)
  27. }
  28. window.addEventListener("message", function() {
  29. $("textarea").value += "\nson say: " + event.data
  30. })
  31. var son = window.open("myson.html")
  32. function keydown() { //这里不需要传递参数,直接使用event就可以
  33. if (event.keyCode == 13) {
  34. son.postMessage($("input").value, location.href)
  35. $("textarea").value += "\n我说:" + $("input").value
  36. $("input").value = ""
  37. event.preventDefault
  38. }
  39. }
  40. </script>
  41. </html>

myson.html


    
    
  1. <html>
  2. <head>
  3. <style>
  4. textarea,
  5. input {
  6. width: 80%;
  7. font-size: 20px;
  8. font-family: "Consolas";
  9. }
  10. textarea {
  11. height: 80%;
  12. }
  13. input {
  14. height: 10%;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div style="text-align:center">
  20. <textarea readonly></textarea>
  21. <input type="text" style="margin-top:10px" onkeydown="keydown()">
  22. </div>
  23. </body>
  24. <script>
  25. var father = null
  26. window.addEventListener("message", function() {
  27. $("textarea").value += "\nfather say: " + event.data
  28. if (father == null) {
  29. father = {
  30. source: event.source,
  31. origin: event.origin
  32. }
  33. }
  34. })
  35. function $(sel) {
  36. return document.querySelector(sel)
  37. }
  38. function keydown() { //这里不需要传递参数,直接使用event就可以
  39. if (event.keyCode == 13) {
  40. father.source.postMessage($("input").value, location.href)
  41. $("textarea").value += "\n我说:" + $("input").value
  42. $("input").value = ""
  43. event.preventDefault
  44. }
  45. }
  46. </script>
  47. </html>

五、最后一个demo


    
    
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. </head>
  5. <body>
  6. <input type="button" value="Open Window" onclick="openWin()" />
  7. </body>
  8. <script>
  9. window.addEventListener("message", function(evt) {
  10. var ele = document.createElement("pre")
  11. ele.innerText = "son say:" + JSON.stringify(evt.data)
  12. document.querySelector("body").appendChild(ele)
  13. })
  14. var popupwin = window.open("son.html");
  15. //onload只能执行一次,也就是如果子窗口有onload事件,可能会覆盖。
  16. popupwin.onload = function(e) {
  17. var params = "天下大势为我所控"
  18. var origin = location.href
  19. popupwin.postMessage(params, origin);
  20. }
  21. popupwin.onunload = function(e) {
  22. var ele = document.createElement("h1")
  23. ele.innerText = "儿子最后说:" + popupwin.returnValue
  24. document.querySelector("body").appendChild(ele)
  25. }
  26. </script>
  27. </html>

son.html


    
    
  1. <html>
  2. <head>
  3. <title>popup window</title>
  4. </head>
  5. <body>
  6. <button onclick="closeWin()">点我返回</button>
  7. <div id="show"></div>
  8. </body>
  9. <script>
  10. function closeWin() {
  11. window.returnValue = "这是返回值";
  12. window.close();
  13. }
  14. //HTML DOM fully loaded, and fired window.onload later.
  15. document.onreadystatechange = function() {
  16. if (document.readyState === 'complete') {
  17. window.addEventListener('message', function(event) {
  18. document.querySelector("#show").appendChild(document.createTextNode("father say:" + e.data))
  19. event.source.postMessage("what's the fuck", event.origin)
  20. });
  21. }
  22. };
  23. </script>
  24. </html>

六、安全问题

如果您不希望从其他网站接收message,请不要为message事件添加任何事件侦听器。
如果您确实希望从其他网站接收message,请始终使用origin和source属性验证发件人的身份。
当您使用postMessage将数据发送到其他窗口时,始终指定精确的目标origin,而不是*。

参考资料

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值