1. 程式人生 > >H5 api之window.postMessage實現跨域視窗通訊(iframe嵌入)

H5 api之window.postMessage實現跨域視窗通訊(iframe嵌入)

官網傳送門

我用的sublimeServer外掛伺服器。

直接上程式碼!!

主頁面:

<!DOCTYPE html>
<html>
<head>
    <title>Post Message</title>
</head>
<body>
    <div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
        <div id="color">Frame Color</div>
    </div>
    <div>
        <iframe id="child" src="http://localhost:8080/self/testpostmessage/testsave.html"></iframe>
    </div>

    <script type="text/javascript">

        window.onload=function(){
            var targetOrigin = 'http://localhost:8080/self/testpostmessage/testsave.html';
            window.frames[0].postMessage('getcolor','http://localhost:8080/self/testpostmessage/testsave.html');
        };

        window.addEventListener('message',function(e){
            
            var color=e.data;
            document.getElementById('color').style.backgroundColor=color;
            
            
        },false);
    </script>
</body>
</html>

iframe內部頁面

<!doctype html>
<html>
    <head>
        <style type="text/css">
            html,body{
                height:100%;
                margin:0px;
            }
        </style>
    </head>
    <body style="height:100%;">
        <div id="container" onclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
            click to change color
        </div>
        <script type="text/javascript">
            var container=document.getElementById('container');

            window.addEventListener('message',function(e){
                if(e.source!=window.parent) return;
                var color=container.style.backgroundColor;
                window.parent.postMessage(color,'*');
                // console.log(e.origin);
                if(e.origin=='http://localhost:8080/self/testpostmessage/test1.html'){
                    console.log(e.origin)
                }
            },false);

            function changeColor () {            
                var color=container.style.backgroundColor;
                if(color=='rgb(204, 102, 0)'){
                    color='rgb(204, 204, 0)';
                }else{
                    color='rgb(204,102,0)';
                }
                container.style.backgroundColor=color;
                console.log(window.parent.postMessage);
                window.parent.postMessage(color,'*');
            }
        </script>
    </body>
</html>

需要注意的幾個點:

1、子頁面一定要在主頁面監聽message之前監聽message

2、window.parent.postMessage(color,'*') 第一個引數為要傳送的資料,第二個限定接收的主頁面url(只識別到協議主機埠號)*為所有都可接收

3、window.frames[0].postMessage('getcolor','http://localhost:8080/self/testpostmessage/testsave.html');主頁面這句話的兩個引數沒多大卵用

3.1:父傳子也可以。

4、接收資料e的主要屬性:

  1. data:顧名思義,是傳遞來的message
  2. source:傳送訊息的視窗物件
  3. origin:傳送訊息視窗的源(協議+主機+埠號)

so可以看一下html5另一個API——web workers了

來個紅心,關注唄~