Skip to content

Instantly share code, notes, and snippets.

@ufologist
Created August 8, 2016 08:05
Show Gist options
  • Select an option

  • Save ufologist/621f11183377780f54d401611536a18a to your computer and use it in GitHub Desktop.

Select an option

Save ufologist/621f11183377780f54d401611536a18a to your computer and use it in GitHub Desktop.

Revisions

  1. ufologist created this gist Aug 8, 2016.
    44 changes: 44 additions & 0 deletions a-domain.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>a-domain</title>
    </head>
    <body>
    <h1>跨域通信机制 - postMessage</h1>
    <h2>a-domian.html</h2>
    <iframe class="js-iframe" src="http://localhost:3000/other-domain.html"></iframe>
    <script>
    function sendMessage2Child() {
    var iframe = document.querySelector('.js-iframe');
    var iframeWindow = iframe.contentWindow;

    // 注意: 必须在 iframe onload 之后父级才能给子级发消息
    iframe.onload = function() {
    // targetOrigin: iframe(消息接收者)所在的域名, 即目标的域名
    // 可以这样简单的记忆: 调用 window.postMessage 时, 这个 window 所在的域名
    // 例如
    // * 使用 iframe.contentWindow 指的就是 iframe 所在的域名
    // * 在 iframe 中使用 parent.postMessage 即 parent 所在的域名
    //
    // 因此你没有办法伪造域名, 因此不到万不得已, 不要使用 "*"
    var targetOrigin = 'http://localhost:3000';
    // 要发送消息给谁, 就使用谁的 window 对象
    iframeWindow.postMessage('在父级发送消息给子级(父级给子级的数据)', targetOrigin);
    };
    }

    function receiveChildMessage() {
    // 监听子级给父级发送过来的消息
    window.addEventListener('message', function(event) {
    // event.origin: 消息来源(发消息的人)
    // 正式环境下一般都需要做消息来源的过滤以免出现安全问题
    console.log('消息传递', event.origin, '->', window.location.href, event.data);
    }, false);
    }

    sendMessage2Child();
    receiveChildMessage();
    </script>
    </body>
    </html>
    30 changes: 30 additions & 0 deletions other-domain.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>other-domain.html</title>
    </head>
    <body>
    <h1>other-domain.html</h1>
    <script>
    function receiveParentMessage() {
    // 监听父级给子级发送过来的消息
    window.addEventListener('message', function(event) {
    console.log('消息传递', event.origin, '->', window.location.href, event.data);
    // 可以在这里通过 event.source 给父级发送消息
    // event.source.postMessage('子级->父级', 'http://localhost:8000');
    }, false);
    }

    function sendMessage2Parent() {
    // 调用 parent.postMessage, targetOrigin 为 parent 所在的域名
    var targetOrigin = 'http://localhost:8000';
    // 子级发送消息给父级
    parent.postMessage('在子级发送消息给父级(子级给父级的数据)', targetOrigin);
    }

    receiveParentMessage();
    sendMessage2Parent();
    </script>
    </body>
    </html>