[读书笔记]Communication API

本文介绍跨文档消息通信的概念与实现方法,并通过企鹅聊天模拟演示了两个源之间的安全通信过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1.1 跨文档消息通信
跨文档消息通信可以确保iframe、标签页、窗口间安全地进行跨源通信。
posetMessage API 发送小心
chatFrame。contentwindow.postMessage("hello world", "http://www.example.com/")
接受消息需在页面增加一个事件处理函数。当某个消息到达时, 通过检查消息的来源(origin)
来决定是否对这条消息进行处理。
window.addEventListener("message", messageHandler, true)
function messageHandler(e) {
     switch(e.origin) {
     case "friend.example.com":
          processMessage(e.data);
          break;
     default:
          break;     
     }
}


1.2 理解源
源由规则(scheme)、主机(host)、端口(port)组成。

1.3 使用postMessage API
模拟qq聊天,两个源之间的通信: 闪烁显示有信息来了。
one_communication.html:
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8">
<link rel= "stylesheet" type ="text/css" href="./main.css"/>
<title> 聊天</ title>
</head>
<body>
      <h1 >企鹅哥哥 </h1 >
      <p >网络地址:http://localhost:8888 </p >
      <div >
             <div >
                   <span id ="statusChange" style="color: blue">等待企鹅妹妹的消息中... </span > <br />
                   <input type ="button" id="readMsg" value= "点击读消息" ></input >
             </div >
             <div >
                   <span id ="receiveAllMsg" style="color: blue;"></span >
                   <input id ="receiveMsg" type="hidden"></ input>
             </div >
      </div ><br />
      <div >
             <p >发送消息给企鹅妹妹: </p >
             <input type ="text" id="message" value= "企鹅妹妹好啊" size= 80></ input>
             <button id ="sendMsg">查看消息</ button>
      </div >
      <br />
      <iframe id ="widget" src= "http://localhost:9999/the_other_communication.html" ></iframe >
</body>
<script type= "text/javascript" src="./jquery-2.1.1.js" ></script >
<script type= "text/javascript" src="./one_communication.js" ></script >
</html>

one_communication.js:
var notificationTimer = null;

var trustedOrigin = "http://localhost:9999" ;

//消息处理函数
function messageHandler(e) {
      if (e.origin == trustedOrigin) {
            notify(e.data);
      } else {
             //忽略其他源发来的消息
      }
}

function notify(message) {
      stopBlinking();
      if (message != "" ) {
             message = "企鹅妹妹:" + message;
            $( "#receiveMsg").val($( "#receiveMsg").val() + "<br/>" + message);
            blinkMsg( "blue", "red");
      }
}

//停止闪烁
function stopBlinking() {
      if (notificationTimer !== null) {
            clearTimeout(notificationTimer);
      }
}

//闪烁
function blinkMsg(col_1, col_2) {
      $("#statusChange").html( "企鹅妹妹来消息啦" );
      $("#statusChange").css( "color", col_1);
      notificationTimer = setTimeout(blinkMsg, 1000, col_2, col_1);
}

//发送消息
function sendMessage() {
      var message = $( "#message").val();
      document.getElementById( "widget").contentWindow.postMessage(message, trustedOrigin);
      $("#message").val( "");
}

//读消息
function readMessage() {
      stopBlinking();
      $("#receiveAllMsg").append($( "#receiveMsg").val());
      $("#receiveMsg").val( "");
      $("#statusChange").html( "等待企鹅妹妹的消息中..." );
      ("#statusChange").css( "color", "blue");
}


$(function () {
      $("#sendMsg").bind( "click", sendMessage);
      $("#readMsg").bind( "click", readMessage);
      
      //绑定消息接收的监听器
      window.addEventListener( "message", messageHandler, true);
});

the_other_communication.html
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8">
<title> 聊天</ title>
</head>
<body>
      <h1 >企鹅妹妹 </h1 >
      <p >网络地址: http://localhost:9999 </p >
      <p >企鹅哥哥的留言: <strong id ="receiveMsg"></ strong></ p>
      <div >
             <input type ="text" id="sengMsg" value= "企鹅哥哥,想你了" size= "80"></input >
             <button id ="sendMsgBtn">发消息给企鹅哥哥</button >
      </div >
</body>
<script type= "text/javascript" src="./jquery-2.1.1.js" ></script >
<script type= "text/javascript" src= "./the_other_communication.js"></script >
</html>

the_other_communication.js

var trustedOrigin = "http://localhost:8888" ;
function messageHandler(e) {
      if (e.origin === trustedOrigin) {
            $( "#receiveMsg").html(e.data);
      } else {
             //忽略其他源发来的消息
      }
}

$(function () {
      $("#sendMsgBtn").click( function () {
             var msg = $( "#sengMsg").val();
             if (msg != "") {
                  window.top.postMessage(msg, trustedOrigin);
            }
            $( "#sengMsg").val( "");
      });
      
      window.addEventListener( "message", messageHandler, true);
});

1.4 搭建以上代码运行代码
1)安装python2.7,非3.x版本。
2)运行web服务器
python -m SimpleHTTPServer 8888
python -m SimpleHTTPServer 9999
3)Firefox上运行http://localhost:8888/one_communication.html

1.5 运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值