登录  /  注册
首页 > web前端 > H5教程 > 正文

详解HTML5中的消息通信代码

零下一度
发布: 2017-04-22 14:38:51
原创
1601人浏览过

html5支持跨文档消息通信(cross-document messaging)。

既然使用到消息通信,那么必然有事件(event)产生。根据事件的产生和消费,我们能够找到发送者和接收者,也就是Sender和Listener。

其中Litener需要做如下的工作:

  1. 编写一个消息处理函数;

  2. 将消息处理函数注册:addEventListener('message', function, false);

其中Sender需要做以下工作:

  1. postMessage('this is a message', 'http://www.php.cn');

事件对象event中包含的成员包括:

  1. data:传递的数据;

  2. origin:origin,origin包括三要素:主机、协议、端口;

  3. source:来源对象;

好了,下面我们看一个例子,这个例子展示了在页面中嵌套页面并且向子页面发送消息:

父页面如下:

<!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中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号