温馨提示×

温馨提示×

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

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

html5中如何解决跨域通信的问题

发布时间:2022-01-20 15:51:11 来源:亿速云 阅读:178 作者:iii 栏目:开发技术

这篇文章主要介绍“html5中如何解决跨域通信的问题”,在日常操作中,相信很多人在html5中如何解决跨域通信的问题问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”html5中如何解决跨域通信的问题”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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" >
     我是主界面,等待接收iframe的传递
  </div>
  <div >
     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 >
        <div id="frame"  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中如何解决跨域通信的问题”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

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

AI