• postMessage解决跨域跨窗口消息传递


    平时做web开发的时候关于消息传递,除了客户端与服务器传值还有几个经常会遇到的问题

    1. 页面和其打开的新窗口的数据传递
    2. 页面与嵌套的iframe消息传递

    这些问题都有一些解决办法,但html5引入的message的API可以更方便、有效、安全的解决这些难题。
    postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

    语法

    otherWindow.postMessage(message, targetOrigin, [transfer]);
    

    otherWindow

    其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。

    message

    将要发送到其他 window的数据。

    targetOrigin

    通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串'*'(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的origin属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是*。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。

    例子

    现在有2个网站页面,分别是http://testA.com/A.htmlhttp://testB.com/B.html

    // A.html嵌套B.html
    // A.html 
    // A向B传递消息
    window.onload = function () {
        window.frames[0].postMessage('getcolor', 'http://testB.com');
    }
    // A接收B的消息
    window.addEventListener('message', function (e) {
        if (e.source != 'http://testB.com') return;
        alert(JSON.stringify(e));
    }, false);
    
    // B.html
    // B向A传递消息
    function Send () {
        window.parent.postMessage(color, 'http://testA.com');
    }
    // B接收A的消息
    window.addEventListener('message', function (e) {
        if (e.source != 'http://testA.com') return;
        alert(JSON.stringify(e));
    }, false);
    
    
    // A.html新开窗口B.html
    // A.html 
    // A向B传递消息
    let win = null;
    window.onload = function () {
        win = window.open('http://testB.com');
    }
    function Send () {
        win.postMessage(color, 'http://testB.com');
    }
    // A接收B的消息
    window.addEventListener('message', function (e) {
        if (e.source != 'http://testB.com') return;
        alert(JSON.stringify(e));
    }, false);
    
    // B.html
    // B向A传递消息
    function Send () {
        window.opener.postMessage(color, 'http://testA.com');
    }
    // B接收A的消息
    window.addEventListener('message', function (e) {
        if (e.source != 'http://testA.com') return;
        alert(JSON.stringify(e));
    }, false);
    
  • 相关阅读:
    CNN做序列标注问题(tensorflow)
    对于梯度消失和梯度爆炸的理解
    LSTM(长短期记忆网络)及其tensorflow代码应用
    Python之禅
    Python namedtuple
    Linux里的2>&1
    PySpark笔记
    平衡二叉树,B树,B+树
    lzo文件操作
    Hadoop的Shell命令
  • 原文地址:https://www.cnblogs.com/kw13202/p/10391580.html
Copyright © 2020-2023  润新知