html5新机制:postMessage如何实现安全跨域通信

发布时间:2020-10-22 16:58:29 作者:小新
来源:亿速云 阅读:152

这篇文章将为大家详细讲解有关html5新机制:postMessage如何实现安全跨域通信,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

效果图

html5新机制:postMessage如何实现安全跨域通信

postmessage解析

实现方式

主界面 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>
  <p id="main1" style="width:200px;height:200px;margin:100px;border:solid 1px #000;">
     我是主界面,等待接收iframe的传递
  </p>
  <p style="margin:100px;">
     iframe
     <iframe src="http://localhost:3000/iframe.html" width="800px" height="300px" ></iframe>
  </p>
</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%;">
        <p id="frame" style="height:200px; width:200px;background-color:rgb(204, 204, 0)" onclick="changeColor()">
           点击改变颜色
        </p>
        <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如何实现安全跨域通信就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. html5中postMessage如何解决跨域通信的问题
  2. HTML5中postMessage实现跨域的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

html5 age st

上一篇:android 使用Xml文件定义Shape方式

下一篇:使用手机连接云服务器教程

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》