zoukankan      html  css  js  c++  java
  • JavaScript 跨域:window.postMessage 实现跨域通信

        JavaScript 跨域方式实现方式有很多,之前,一篇文章中提到了 JSONP 形式实现跨域。本文将介绍 HTML5 新增的 api 实现跨域:window.postMessage 。

      

     1 otherWindow.postMessage(message, targetOrigin);
     2 
     3 otherWindow
     4 其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
     5 
     6 message
     7 将要发送到其他 window的数据。将会被结构化克隆算法序列化。这意味着你可不受什么限制的安全传送数据对象给目标窗口而无需自己序列化。
     8 
     9 targetOrigin
    10 该参数可设置为 *,将无域名限制。也可指定特定的域名,比如:http://www.jj.com
    11 
    12 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

        本文还是以 iframe 为例,一个 html 页面中套有一个 iframe 文档,不过,iframe 文档 src 属性与 html 页面不同域,因此,两者之间便形成跨域。

         index.html _http://localhost:3127/index.htm 

    <!DOCTYPE html >
    <html >
    <head>
        <title></title>
    </head>
    <body >
       <input type="text"  id="val"/>
        <input type="button" id="btn" value="测试" /><br/>
        
        <iframe src="http://localhost:10528/index.html" > </iframe>
        <script type="text/javascript">
            window.onload = function () {
    // 首先,给按钮绑定 click 事件
    if (window.addEventListener)
    document.getElementById(
    'btn').addEventListener('click', sendMsg, false); else document.getElementById('btn').attachEvent("onclick", sendMsg); };
    // 获取 iframe 标签,利用 postMessage 跨域通信,值为 input text 标签值
    function sendMsg() { document.getElementsByTagName('iframe')[0].contentWindow.postMessage(document.getElementById('val').value,"*"); } </script> </body> </html>

      index.html (iframe) _http://localhost:10528/index.html

    <!DOCTYPE html >
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    
    </head>
    <body >
       <b>我是另一个跨中 iframe 文档</b>
        <script type="text/javascript">

    // 给 iframe 文档绑定 message 事件 window.onload = function () { if (window.addEventListener) window.addEventListener('message', getMessage, false); else window.attachEvent("onmessage", getMessage); };
    // iframe 触发 message 事件时,调用 getMessage 函数
    function getMessage(event) { console.dir(event); alert(event.data); } </script> </body> </html>


     

    参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

  • 相关阅读:
    理想解法
    IEEExtreme 2021
    day_1-python前期学习准备篇
    电梯模拟C++
    java线程_01——————————HelloWorld例子
    Unknown tag (c:forEach) 未知的标签
    自动生成Junit单元测试的插件 CodeProAnalytix
    Log4j笔记----01
    Springboot学习笔记_helloWorld篇
    支持开源,崇尚技术,追求真理,充实人生
  • 原文地址:https://www.cnblogs.com/Lumia1020/p/5505346.html
Copyright © 2011-2022 走看看