>  기사  >  웹 프론트엔드  >  HTML5 window.postMessage 및 도메인 간 튜토리얼

HTML5 window.postMessage 및 도메인 간 튜토리얼

零下一度
零下一度원래의
2017-05-13 13:14:361601검색

본 글에서는 HTML5 window.postMessage와 크로스 도메인에 대한 자세한 설명을 주로 소개하고 있는데, 도움이 필요한 친구들이 참고할 수 있을 만큼 유용합니다.

이전 글에서 에서 브라우저의 동일 출처 정책은 서로 다른 도메인의 페이지가 서로의 메소드 및 속성에 액세스하는 것을 방지합니다. 또한 동일 출처 정책의 도메인 간 문제를 해결하기 위해 제안된 솔루션인 하위 도메인 프록시, JSONP 및 CORS에 대해서도 설명합니다. . 이 기사에서는 HTML5 window.postMessage에 대해 자세히 설명합니다. postMessage API를 사용하면 안전하고 제어 가능한 방식으로 문서 간 도메인 간 통신이 가능하며, 타사 JavaScript 코드도 iframe에 로드된 외부 문서와 통신할 수 있습니다.

HTML5 window.postMessage API

HTML5 window.postMessage는 안전한 이벤트 기반 메시징 API입니다.

postMessage가 메시지를 보냅니다

메시지를 보내야 하는 소스 창에서 postMessage 메소드를 호출하여 메시지를 보냅니다.

소스 창

소스 창은 전역 창 개체이거나 다음 유형의 창일 수 있습니다.

문서 창의 iframe:

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

JavaScript로 연 팝업 창:

var win = window.open();

현재 문서 창의 상위 창:

var win = window.parent;

현재 문서의 창 열기:

var win = window.opener();

소스 창 객체 찾기 그 후 postMessage API를 호출하여 대상 창에 메시지를 보낼 수 있습니다:

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

postMessage 함수는 두 개의 매개변수를 받습니다. 첫 번째는 메시지입니다. 전송되고 두 번째는 소스 창의 소스입니다.

참고: 메시지는 대상 창의 소스가 postMessage 함수에 전달된 소스 매개변수 값과 일치하는 경우에만 수신될 수 있습니다.

postMessage 메시지 받기

이전에 소스 창에서 postMessage를 통해 보낸 메시지를 받으려면 대상 창에 메시지 이벤트를 등록하고 이벤트를 바인딩하기만 하면 됩니다. 메시지는 기능 매개변수에서 얻을 수 있습니다.


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);
        }
    };

메시지 이벤트 수신 함수는 세 가지 속성이 있는 이벤트 개체 인스턴스인 매개변수를 받습니다.

  1. 데이터 전송 메시지

  2. origin 메시지 보내기 소스

  3. source 메시지 보내기 창 창 개체참조

참고

  1. postMessage 함수의 두 번째 매개변수를 *로 설정할 수 있습니다. 이렇게 하면 도메인 간 메시지를 보낼 때 메시지 소스 확인을 건너뛸 수 있습니다. . 점검.

  2. postMessage는 문자열 정보만 보낼 수 있습니다.

인스턴스

소스 창

<!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>

대상 창 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>

복습

이 기사를 통해 HTML5의 postMessage API를 사용하여 창 간 통신을 수행하는 방법과 이를 현대적인 도메인 간 통신에 사용할 수 있다는 사실을 배웠습니다. 브라우저는 기본적으로 postMessage를 지원하며 IE7 등 일부 오래된 브라우저의 경우 window.name, urlquery 문자 및 hash와 같은 특정 대안을 데이터 통신에 사용할 수 있습니다. 파편 등

【관련 추천】

1. 특별 추천: "php Programmer Toolbox" V0.1 버전 다운로드

2. 무료 h5 온라인 동영상 튜토리얼

3. php.cn 원본 html5 동영상 튜토리얼

위 내용은 HTML5 window.postMessage 및 도메인 간 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.