HTML5中的消息通信

本文英文教程来源:Lynda.com.HTML5.Messaging.And.Communications.In.Depth


HTML5支持跨文档消息通信(Cross-Document Messaging)。


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

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

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

其中Sender需要做以下工作:

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

事件对象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 = 'http://two.3sn.net';
		// URL地址
        var URLTwo = 'http://two.3sn.net/H5Msg/ExerciseFiles/Chap01/crossDomainTwo.html';
        var windowTwo = null;

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


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

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

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

        function clearDisp() {
            element('pageResults').innerHTML = '';
            element('message').innerHTML = '';
            element('message').className = '';
        }

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

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

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

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

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

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

        window.onload = init;

    </script>
</head>

<body>

<div id="content">

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

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

    <iframe id="frameTwo">
        <p>Your browser doesn't support the iFrame feature</p>
    </iframe>

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

</div>
</body>
</html>


子页面的内容,实际上页面放在http://two.3sn.net/H5Msg/ExerciseFiles/Chap01/crossDomainTwo.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 = 'http://one.3sn.net';

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

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

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

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

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

        function clearDisp() {
            element('pageResults').innerHTML = '';
            element('message').innerHTML = '';
            element('message').className = '';
        }

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

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

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

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

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

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

        window.onload = init;

    </script>
</head>

<body>

<div id="content">

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

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

</div>
</body>
</html>







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值