详解html5 postMessage解决跨域通信的问题

2022-10-20,,,,

本文介绍了详解html5 postmessage解决跨域通信的问题,分享给大家,具体如下:

效果图

postmessage解析html5提供了新型机制postmessage实现安全的跨源通信. 语法 otherwindow.postmessage(message, targetorigin, [transfer]);

otherwindow: 其他窗口的一个引用, 比如iframe的contentwindow属性, 执行,window.open返回的窗口对象. message: 将要发送到其他窗口的数据. targetorigin:通过窗口的origin属性来指定哪些窗口能接收到消息事件, 其值可以是字符”*”(表示无限制)或者一个url transfer:是一串和message同时传递的transferable对象. 这些对象的所有权将被转移给消息的接收方, 而发送一放将不再保有所有权.element.addeventlistener(event,fn,usecaption ); 三个参数 event 事件 比如click mouseenter mouseleave 回调函数 usecaption用于描述是冒泡还是捕获。默认值是false,即冒泡传递。 当值为true,就是捕获传递。实现方式

主界面 main.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>跨域数据访问</title>
  <script type="text/javascript">
         window.addeventlistener('message',function(e){
           console.log("e--->",e);
           const data = e.data;
           document.getelementbyid('main1').style.backgroundcolor=e.data;
         },false)

  </script>
</head>
<body>
  <div id="main1" style="width:200px;height:200px;margin:100px;border:solid 1px #000;">
     我是主界面,等待接收iframe的传递
  </div>
  <div style="margin:100px;">
     iframe
     <iframe src="http://localhost:3000/iframe.html" width="800px" height="300px" ></iframe>
  </div>
</body>
</html>

iframe界面

<!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 type="text/css">
           html,body{
               height:100%;
               margin:0px;
           }
    </style>
</head>
  <body style="height:100%;">
        <div id="frame" style="height:200px; width:200px;background-color:rgb(204, 204, 0)" onclick="changecolor()">
           点击改变颜色
        </div>
        <script type="text/javascript">
             function changecolor(){
               var frame = document.getelementbyid('frame');
               var color=frame.style.backgroundcolor;
               if(color=='rgb(204, 102, 0)'){
                   color='rgb(204, 204, 0)';
               }else{
                   color='rgb(204,102,0)';
               }
                console.log("frame===>",frame);
                console.log("color",color);
               frame.style.backgroundcolor=color;
               window.parent.postmessage(color,'*');
             }
        </script>
  </body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《详解html5 postMessage解决跨域通信的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。