扣丁学堂HTML5培训详解HTML5 postMessage解决跨域通讯的问题

本篇文章扣丁学堂HTML5培训小编给读者们分享一下HTML5 postMessage解决跨域通讯的问题,文中有代码列出供小伙伴们参考,感兴趣的小伙伴就随小编来了解一下吧。javascript

otherWindow:其余窗口的一个引用, 好比IFRAME的contentWindow属性, 执行,window.open返回的窗口对象。css

message:将要发送到其余窗口的数据。html

targetOrigin:经过窗口的origin属性来指定哪些窗口能接收到消息事件, 其值能够是字符”*”(表示无限制)或者一个URL。java

transfer:是一串和message同时传递的Transferable对象。跨域

这些对象的全部权将被转移给消息的接收方, 而发送一放将再也不保有全部权.element.addEventListener(event,fn,useCaption ); 三个参数 event 事件 好比click mouseenter mouseleave 回调函数 useCaption用于描述是冒泡仍是捕获。默认值是false,即冒泡传递。 当值为true,就是捕获传递。微信

实现方式:函数

主界面 main.htmlpost

<!DOCTYPE html>学习

<html lang="en">ui

<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方面内容的小伙伴,请关注扣丁学堂HTML5培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的HTML5视频,HTML5培训后的前景无限,行业薪资和将来的发展会愈来愈好的,扣丁学堂老师精心推出的HTML5视频教程定能让你快速掌握HTML5从入门到精通开发实战技能。

相关文章
相关标签/搜索