zoukankan      html  css  js  c++  java
  • postMessage使用测试

    1. 父页面

    <html>
    <head>
        <meta charset="gbk">
        <title>引用页面</title>
    </head>
    <body>
    <button id='openNewWindow'>弹出新窗口</button>
    <button id='sendMessage'>发送消息</button>
    <input id='message' value='0'>
    <iframe id='childWindow' src="test03-2.html"></iframe>
    <script type="text/javascript">
        var childWindow = document.getElementById('childWindow');
        openNewWindow.onclick = function(){
            window.w=window.open('test03-2.html');
        }
        window.onmessage=function(e){
            console.log(e);
            message.value = +message.value + 1;
        };
        sendMessage.onclick = function(){
            w.postMessage({sendby: 1, m: 'test'}, '*');
            childWindow.contentWindow.postMessage({sendby: 1, m: 'test'}, '*');
        };
    </script>
    </body>
    </html>

    2. 子页面

    <html>
    <head>
        <meta charset="gbk">
        <title>被引用页面</title>
    </head>
    <body>
        <button id='sendMessage'>发送消息</button>
        <input id='message' value='0'>
    <script type="text/javascript">
        parent.onmessage=function(e){
            console.log(e);
            message.value = +message.value + 1;
        };
        window.onmessage=function(e){
            console.log(e);
            message.value = +message.value + 1;
        };
        sendMessage.onclick = function(){
            parent.postMessage({sendby: 2, m: 'test'}, '*');
        };
    </script>
    </body>
    </html>

    tips:iframe引入的页面,可以相互通信;window.open打开的页面只能父页面向子页面发消息。

  • 相关阅读:
    Nightmare Ⅱ HDU
    Full Tank? POJ
    2601 电路维修 (双端队列bfs优先队列bfs(最短路))
    Sudoku POJ
    Pushing Boxes POJ
    2501 矩阵距离 (bfs)
    【排序】绝境求生
    【排序】逆序对IV
    【排序】紧急集合
    【排序】常用排序法
  • 原文地址:https://www.cnblogs.com/snadn/p/3142372.html
Copyright © 2011-2022 走看看