Home > Web Front-end > H5 Tutorial > body text

HTML5 window.postMessage and cross-domain example tutorial

零下一度
Release: 2017-05-13 13:14:36
Original
1639 people have browsed it

This article mainly introduces the detailed explanationHTML5 window.postMessage and cross-domain, which are of great practical value. Friends in need can refer to it

In the previous article, we talked about The browser's same-origin policy prevents pages from different domains from accessing each other's methods and attributes. It also explains the solutions proposed to solve the cross-domain problem of the same-origin policy: subdomain proxy, JSONP, and CORS. This article will elaborate on HTML5 window.postMessage. With the postMessage API, cross-domain communication can be achieved between documents in a safe and controllable manner. Third-party JavaScript code can also communicate with external documents loaded in iframes.

HTML5 window.postMessage API

HTML5 window.postMessage is a secure, event-based messaging API.

postMessage sends a message

Call the postMessage method in the source window where the message needs to be sent to send the message.

Source window

The source window can be a global window object or the following types of windows:

iframe in the document window:

var iframe = document.getElementById('my-iframe');
    var win = iframe.documentWindow;
Copy after login

Pop-up window opened by JavaScript:

var win = window.open();
Copy after login

The parent window of the current document window:

var win = window.parent;
Copy after login

Open the window of the current document:

var win = window.opener();
Copy after login

Find the source window object After that, you can call the postMessage API to send a message to the target window:

``win.postMessage('Hello', 'ttp://jhssdemo.duapp.com/');"
Copy after login

postMessageFunctionReceives two parameters: the first is the message to be sent, and the second is the source of the source window .

Note: The message can only be received when the source of the target window matches the source parameter value passed in the postMessage function.

Receive postMessage message

To receive the message previously sent by the source window through postMessage, you only need to register the message event in the target window and bind the event listening function. The message can be obtained in Function parameters.


window.onload = function() {
        var text = document.getElementById('txt');  
        function receiveMsg(e) {
            console.log("Got a message!");
            console.log("nMessage: " + e.data);
            console.log("nOrigin: " + e.origin);
            // console.log("Source: " + e.source);
            text.innerHTML = "Got a message!<br>" +
                "Message: " + e.data +
                "<br>Origin: " + e.origin;
        }
        if (window.addEventListener) {
            //为窗口注册message事件,并绑定监听函数
            window.addEventListener(&#39;message&#39;, receiveMsg, false);
        }else {
            window.attachEvent(&#39;message&#39;, receiveMsg);
        }
    };
Copy after login

message event listening function receives a parameter, an Event object instance, which has three attributes:

  1. data sent Message

  2. origin Send message source

  3. source Send message window window objectReference

Explanation

  1. You can set the second parameter of the postMessage function to *, and when sending a cross-domain message, the source of the message will be skipped. inspection.

  2. postMessage can only send string information.

Example

Source window

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Html5 postMessage</title>
        <style>
            #otherWin {
                width: 600px;
                height: 400px;
                background-color: #cccccc;
            }
        </style>
    </head>
    <body>
        <button id="btn">open</button>
        <button id="send">send</button>
         <!-- 通过 iframe 嵌入子页面(接收消息目标窗口) --> 
         <iframe src="http://jhssdemo.duapp.com/demo/h5_postmessage/win.html" 
                     id="otherWin"></iframe> 
         <br/><br/> 
         <input type="text" id="message"><input type="button" 
                 value="Send to child.com" id="sendMessage" /> 
        <script>
            window.onload = function() {
                var btn = document.getElementById(&#39;btn&#39;);
                var btn_send = document.getElementById(&#39;send&#39;);
                var sendBtn = document.getElementById(&#39;sendMessage&#39;);
                var win;
                btn.onclick = function() {
                    //通过window.open打开接收消息目标窗口
                    win = window.open(&#39;http://jhssdemo.duapp.com/demo/h5_postmessage/win.html&#39;, &#39;popUp&#39;);
                }
                btn_send.onclick = function() { 
                    // 通过 postMessage 向子窗口发送数据      
                    win.postMessage(&#39;Hello&#39;, &#39;http://jhssdemo.duapp.com/&#39;);
                }
                function sendIt(e){ 
                    // 通过 postMessage 向子窗口发送数据
                    document.getElementById("otherWin").contentWindow 
                    .postMessage( 
                        document.getElementById("message").value, 
                        "http://jhssdemo.duapp.com/"); 
                } 
                sendBtn.onclick = function(e) {
                    sendIt(e);
                };
            };
        </script>
    </body>
    </html>
Copy after login

Target window win.html

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Html5 postMessage</title>
        <style>
            #txt {
                width: 500px;
                height: 300px;
                background-color: #cccccc;
            }
        </style>
    </head>
    <body>
        <h1>The New Window</h1>
        <p id="txt"></p>
        <script>        
            window.onload = function() {
                var text = document.getElementById(&#39;txt&#39;);  
                //监听函数,接收一个参数--Event事件对象
                function receiveMsg(e) {
                    console.log("Got a message!");
                    console.log("nMessage: " + e.data);
                    console.log("nOrigin: " + e.origin);
                    text.innerHTML = "Got a message!<br>" +
                        "Message: " + e.data +
                        "<br>Origin: " + e.origin;
                }
                if (window.addEventListener) {
                    //为window注册message事件并绑定监听函数
                    window.addEventListener(&#39;message&#39;, receiveMsg, false);
                }else {
                    window.attachEvent(&#39;message&#39;, receiveMsg);
                }
            };
        </script>
    </body>
    </html>
Copy after login

Review

Through the study of this article, I learned about using HTML5’s postMessage API to communicate between windows, and also learned that it can be used to achieve cross-domain communication; modern browsers basically support it postMessage, for some old browsers such as IE7-etc., certain alternatives can be used for data communication, such as window.name, url query characters and hash fragments, etc.

【Related Recommendations】

1. Special Recommendation:"php Programmer Toolbox" V0.1 version Download

2. Free h5 online video tutorial

##3.

php.cn original html5 video tutorial

The above is the detailed content of HTML5 window.postMessage and cross-domain example tutorial. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!