HTML5의 메시지 통신 코드에 대한 자세한 설명

零下一度
풀어 주다: 2017-04-22 14:38:51
원래의
1783명이 탐색했습니다.

HTML5는 문서 간 메시징(Cross-Document Messaging)을 지원합니다.

메시지 통신을 사용하기 때문에 이벤트가 발생해야 합니다. 이벤트의 생성과 소비에 따라 송신자와 수신자, 즉 Sender와 Listener를 찾을 수 있습니다.

Litener는 다음 작업을 수행해야 합니다.

  1. 메시지 처리 기능을 작성합니다.

  2. 메시지 처리 기능을 등록합니다. addEventListener('message', function, false);

발신자는 다음을 수행해야 합니다:

  1. postMessage('이것은 메시지입니다 ' , 'http://www.php.cn');

이벤트 개체 이벤트에 포함된 멤버는 다음과 같습니다.

  1. 데이터 : 전달된 데이터

  2. 원본: 원본, 원본에는 호스트, 프로토콜, 포트의 세 가지 요소가 포함됩니다.

  3. 소스: 소스 개체; >

아래 예를 살펴보겠습니다. 이 예는 페이지 내에 페이지를 중첩하고 하위 페이지로 메시지를 보내는 것을 보여줍니다.

상위 페이지는 다음과 같습니다.

<!DOCTYPE html>
<html lang="en">

<!-- 
    crossDomain.html by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 
-->

<head>
    <title>
        HTML5 Messaging Template File (One)
    </title>
    <link rel="stylesheet" type="text/css" href="../CSS/main.css">
    <style>
        #frameTwo {
            float: left;
            width: 500px;
            height: 400px;
            margin: 0 5px;
            padding: 3px;
            border-top: 2px solid #3c6b92;
            border-left: 2px solid #3c6b92;
            border-bottom: 2px solid #ccc;
            border-right: 2px solid #ccc;
        }
        #content { height: 500px; }
    </style>
    <script type="text/javascript">
		// 域名
        var originTwo = &#39;http://two.3sn.net&#39;;
		// URL地址
        var URLTwo = &#39;http://two.3sn.net/H5Msg/ExerciseFiles/Chap01/crossDomainTwo.html&#39;;
        var windowTwo = null;

        function handleMessage(event) {
			// 判断源区域
            if (event.origin == originTwo) {
                if(!windowTwo) windowTwo = event.source;
                log(&#39;message from origin: &#39; + event.origin);
                log(event.data);
				// 发送消息
                windowTwo.postMessage(&#39;this is from windowOne!&#39;, originTwo);
                log(&#39;message sent back to windowTwo&#39;);
            } else {
                dispError(&#39;message from untrusted origin: &#39; + event.origin);
            }
        }


        function init() {
			// 添加消息处理函数
		    window.addEventListener("message", handleMessage, false);
            window.onerror = windowErrorHandler;
            log(&#39;this is windowOne&#39;);
            log(&#39;host: &#39; + location.host);
			
			// load two页面
            element(&#39;frameTwo&#39;).src = URLTwo;   // load the frame
        }

        // ##### Utilities #####

        // shortcut for getElementById
        function element(id) { return document.getElementById(id); }

        function clearDisp() {
            element(&#39;pageResults&#39;).innerHTML = &#39;&#39;;
            element(&#39;message&#39;).innerHTML = &#39;&#39;;
            element(&#39;message&#39;).className = &#39;&#39;;
        }

        function dispMessage(message) {
            m = element(&#39;message&#39;);
            m.className = &#39;message&#39;;
            if(m.textContent.length > 0) {
                m.innerHTML += &#39;<br />&#39; + message;
            } else m.innerHTML = message;
        }

        function windowErrorHandler(message, filename, lineno) {
            dispError(message + &#39; (&#39; + filename + &#39;:&#39; + lineno + &#39;)&#39; );
            return true;
        };

        function dispError(errorMessage) {
            element(&#39;pageResults&#39;).innerHTML += 
                errorMessage ? &#39;<p class="error">&#39; + errorMessage + &#39;</p>\n&#39; : &#39;&#39;;
        }

        function log(m) {
            if(m.length < 1) return;
            logElement = element(&#39;log&#39;);
            if(logElement.textContent.length > 0) logElement.innerHTML += &#39;<br />&#39;;
            logElement.innerHTML += nowTimeString() + &#39; &#39; + m;
        }

        function nowTimeString() {
            var d = new Date();
            return numToString(d.getUTCHours(), 2) + &#39;:&#39; + numToString(d.getUTCMinutes(), 2) + &#39;:&#39; +
                numToString(d.getUTCSeconds(), 2) + &#39;.&#39; + numToString(d.getUTCMilliseconds(), 3);
        }

        function numToString( num, len ) {
            var num = num + &#39;&#39;;
            while(num.length < len) num = &#39;0&#39; + num;
            return num;
        }

        window.onload = init;

    </script>
</head>

<body>

<p id="content">

    <h1> 
        HTML5 Messaging Template File (One)
    </h1>

    <p id="message"></p>
    <p id="pageResults"></p>

    <iframe id="frameTwo">
        <p>Your browser doesn&#39;t support the iFrame feature</p>
    </iframe>

    <p id="log" style="font-family: monospace"></p>

</p>
</body>
</html>
로그인 후 복사
<!DOCTYPE html>
<html lang="en">

<!-- 
    crossDomain.html by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 
-->

<head>
    <title>
        HTML5 Messaging Template File (Two)
    </title>
    <link rel="stylesheet" type="text/css" href="../CSS/main.css">
    <script type="text/javascript">
        var originOne = &#39;http://one.3sn.net&#39;;

        function handleMessage(event) {
            if (event.origin == originOne) {
                log(&#39;message from origin: &#39; + event.origin);
                log(event.data);
            } else {
                dispError(&#39;message from untrusted origin: &#39; + event.origin);
            }
        }

        // ##### Init #####

        function init() {
            window.onerror = windowErrorHandler;    // addEventListener doesn&#39;t provide the right error object in Firefox
            window.addEventListener("message", handleMessage, false);
            log(&#39;this is windowTwo&#39;);
            log(&#39;host: &#39; + location.host);
            var windowOne = parent;
            windowOne.postMessage(&#39;this is from windowTwo!&#39;, originOne);
            log(&#39;message sent to windowOne&#39;);
        }

        // ##### Utilities #####

        // shortcut for getElementById
        function element(id) { return document.getElementById(id); }

        function clearDisp() {
            element(&#39;pageResults&#39;).innerHTML = &#39;&#39;;
            element(&#39;message&#39;).innerHTML = &#39;&#39;;
            element(&#39;message&#39;).className = &#39;&#39;;
        }

        function dispMessage(message) {
            m = element(&#39;message&#39;);
            m.className = &#39;message&#39;;
            if(m.textContent.length > 0) {
                m.innerHTML += &#39;<br />&#39; + message;
            } else m.innerHTML = message;
        }

        function windowErrorHandler(message, filename, lineno) {
            dispError(message + &#39; (&#39; + filename + &#39;:&#39; + lineno + &#39;)&#39; );
            return true;
        };

        function dispError(errorMessage) {
            element(&#39;pageResults&#39;).innerHTML += 
                errorMessage ? &#39;<p class="error">&#39; + errorMessage + &#39;</p>\n&#39; : &#39;&#39;;
        }

        function log(m) {
            if(m.length < 1) return;
            logElement = element(&#39;log&#39;);
            if(logElement.textContent.length > 0) logElement.innerHTML += &#39;<br />&#39;;
            logElement.innerHTML += nowTimeString() + &#39; &#39; + m;
        }

        function nowTimeString() {
            var d = new Date();
            return numToString(d.getUTCHours(), 2) + &#39;:&#39; + numToString(d.getUTCMinutes(), 2) + &#39;:&#39; +
                numToString(d.getUTCSeconds(), 2) + &#39;.&#39; + numToString(d.getUTCMilliseconds(), 3);
        }

        function numToString( num, len ) {
            var num = num + &#39;&#39;;
            while(num.length < len) num = &#39;0&#39; + num;
            return num;
        }

        window.onload = init;

    </script>
</head>

<body>

<p id="content">

    <h1> 
        HTML5 Messaging Template File (Two)
    </h1>

    <p id="message"></p>
    <p id="pageResults"></p>
    <p id="log" style="font-family: monospace"></p>

</p>
</body>
</html>
로그인 후 복사

html5를 배워야 하는 학생들은 PHP 중국어 웹사이트

html5 비디오 튜토리얼에 주목하세요. 많은 html5 온라인 비디오 튜토리얼을 무료로 시청할 수 있습니다!

위 내용은 HTML5의 메시지 통신 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!