工作中遇到一个需求,要在一个比较老的 web 项目中添加新功能,但是最好不要动老项目的代码。
思来想去,就用 iframe 来实现吧,iframe 的内容和老项目的内容互不干扰,数据传输使用 postMessage 来实现。
github地址 
npm地址 
代码
- IframeMsg.js 核心类(封装发送和接收信息的逻辑)
 - index.html 父页面
 - child.html 子页面
 
IframeMsg.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
   | class IframeMsg extends EventTarget {     data; 
      
 
 
      constructor(_window) {         super();         this._window = _window;         this.init();     }
      
 
      init() {         const onMessage = (ev) => {             if (ev.data) {                 const { action, data } = ev.data;                 if (action === undefined) return;                 this.data = ev.data;                 this.dispatchEvent(new Event('message'));             }         };         window.addEventListener('message', onMessage, false);     }
      
 
 
 
      send(action, data) {         this._window.postMessage(             {                 action,                 data             },             '*'         );     } }
  | 
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   | <!DOCTYPE html> <html lang="en">     <head>         <meta charset="UTF-8" />         <meta http-equiv="X-UA-Compatible" content="IE=edge" />         <meta name="viewport" content="width=device-width, initial-scale=1.0" />         <title>iframe通信</title>     </head>
      <body>         <iframe id="child" src="./child.html" frameborder="0"></iframe>
          <script src="./IframeMsg.js"></script>         <script>             let child = document.getElementById('child');
              child.onload = function () {                 let iframeMsg = new IframeMsg(child.contentWindow);
                  iframeMsg.send('jump', '这条信息从父window发送到子window');                 iframeMsg.addEventListener('message', (ev) => {                     console.log(ev.target.data);                     alert(JSON.stringify(ev.target.data));                 });             };         </script>     </body> </html>
   | 
child.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
   | <!DOCTYPE html> <html lang="en">     <head>         <meta charset="UTF-8" />         <meta http-equiv="X-UA-Compatible" content="IE=edge" />         <meta name="viewport" content="width=device-width, initial-scale=1.0" />         <title>iframe通信</title>     </head>
      <body>         <script src="./IframeMsg.js"></script>         <script>             let iframeMsg = new IframeMsg(window.parent);             iframeMsg.addEventListener('message', (ev) => {                 console.log(ev.target.data);                 alert(JSON.stringify(ev.target.data));             });             setTimeout(() => {                 iframeMsg.send('jump', '这条信息从子window发送到父window');             }, 1000);         </script>     </body> </html>
   |