H5 跨域通信:

在主页面中通过iframe嵌入外部页面,通过iframe的window对象postMessage方法向iframe页面传递消息。

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>跨域通信示例</title>
 6         <script type="text/javascript">
 7             function hello(){
 8                 var iframe = document.getElementById("iframe").contentWindow;
 9                 iframe.postMessage("hello, 这是主页面传过来的数据", "http://localhost/html5/b.html");
10             }
11         </script>
12     </head>
13     <body>
14         <h1>跨域通信示例</h1>
15         <iframe width="400" src="http://localhost/html5/b.html" onload="hello()" id="iframe">
16         </iframe>
17     </body>
18 </html>

iframe页面中通过对窗口对象的message事件进行监听,以获取消息。

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <script type="text/javascript">
 6             window.addEventListener("message", getEvent, false);
 7             function getEvent(event){
 8                 alert("" + event.origin + "那里传递过来的信息是:\n" + event.data);
 9             }
10         </script>
11     </head>
12     <body>
13         iframe 页面
14     </body>
15 </html>

  

相关文章:

  • 2022-12-23
  • 2021-06-25
  • 2021-08-21
  • 2022-12-23
  • 2021-11-11
  • 2021-05-08
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2021-10-13
相关资源
相似解决方案