postMessage 实现跨域通信

1. iframe + postMessage

     //主页面:
      var iframe = document.createElement("iframe");
      iframe.src = "http://localhost:3000";
      iframe.id = "myFrame";
      iframe.width = "100%";
      iframe.height = "100%";

      iframe.onload = function () {
        document.getElementById('myFrame').contentWindow.postMessage('主页面消息', 'http://localhost:3000');
      };
      document.body.appendChild(iframe);
     //iframe页 http://localhost:3000:
    window.addEventListener('message', function (event) {
      if(event.origin !== "主页面域名") return;
      console.log(event);
    }, false);

2. window.open() + postMessage

      //主页面:http://192.168.xxx.xxx:5000
      let newWin = window.open("http://localhost:3000");
      let timer = setInterval(() => {
        newWin.postMessage('testtest', 'http://localhost:3000');
      }, 500);
      window.addEventListener('message', function (event) {
        if (event.origin !== 'http://localhost:3000') return;
        if (event.data === 'Received') clearInterval(timer)
      }, false);
    // window.open 页  http://localhost:3000:
    window.addEventListener('message', function (event) {
      if(event.origin !== "http://192.168.xxx.xxx:5000") return;
      event.source.postMessage('Received',event.origin);
    }, false);

猜你喜欢

转载自blog.csdn.net/zzzyyc/article/details/86079636