>  기사  >  웹 프론트엔드  >  H5 window.postMessage 및 교차 도메인

H5 window.postMessage 및 교차 도메인

php中世界最好的语言
php中世界最好的语言원래의
2018-03-26 16:18:282110검색

이번에는 H5 window.postMessage와 크로스 도메인, window.postMessage와 크로스 도메인 Notes를 소개하겠습니다.

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

HTML5 window.postMessage API

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

postMessage메시지 보내기

메시지를 보내려면 메시지를 보내야 하는 소스 창에서 postMessage 메소드를 호출하세요.

소스 창

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

문서 창의 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/');"

The 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('message', receiveMsg, false);
        }else {
            window.attachEvent('message', receiveMsg);
        }
    };

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

  1. data 전송된 특정 메시지

  2. origin 전송된 메시지의 소스

  3. source 창 객체 메시지 창 참조

Explanation

  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('btn');
                var btn_send = document.getElementById('send');
                var sendBtn = document.getElementById('sendMessage');
                var win;
                btn.onclick = function() {
                    //通过window.open打开接收消息目标窗口
                    win = window.open('http://jhssdemo.duapp.com/demo/h5_postmessage/win.html', 'popUp');
                }
                btn_send.onclick = function() { 
                    // 通过 postMessage 向子窗口发送数据      
                    win.postMessage('Hello', 'http://jhssdemo.duapp.com/');
                }
                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('txt');  
                //监听函数,接收一个参数--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('message', receiveMsg, false);
                }else {
                    window.attachEvent('message', receiveMsg);
                }
            };
        </script>
    </body>
    </html>

이 기사의 사례를 읽은 후 방법을 마스터했다고 믿습니다. 기타 관련 기사는 PHP 중국어 웹사이트에 있습니다!

추천 도서:

phonegap으로 위치 정보 획득에 대한 자세한 설명

phonegap으로 연락처 생성에 대한 자세한 설명

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

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