当前位置:Gxlcms > html代码 > HTML5编程之旅-Communication技术初探

HTML5编程之旅-Communication技术初探

时间:2021-07-01 10:21:17 帮助过:17人阅读

   本文主要探讨用于构建实时跨源通信的两个模块:跨文档消息通信(Cross Document Messaging)和XMLHttpRequestLevel2。通过这两个模块,我们可以构建不同域间进行安全通信的Web应用。

一、跨文档消息通信

出于安全方面的看的考虑,运行在同一浏览器中的框架、标签页、窗口间的通信一直多受到严格的限制。但是现实中还存在一些合理的让不同站点的内容能在浏览器内进行交互的需求,其中Mashup就是一个典型的例子,它是各种不同应用的结合体。为了满足上述需求,引入了一种新的功能:跨文档消息通信。其可以确保iframe、标签页、窗口间安全地进行跨源通信。

  发送消息使用postMessage API,其示例代码如下:

  1. chatFrame.contentWindow.postMessage(content,url);

  接受消息时,需要在页面中添加一个事件处理函数,当消息到达时,通过检查消息的来源来决定如何对这条消息如何处理,示例代码如下:

  1. window.addEventListener("message",messageHandler,true);
  2. function messageHandler(e){
  3. switch(e.origin){//表示数据发送源
  4. case "friend.example.com":
  5. //处理消息
  6. processMessage(e.data);//发送方实际传送的消息
  7. break;
  8. default:
  9. //其他消息来源
  10. //消息被忽略。
  11. }
  12. }

  postMessage API提供了一种交互方式,使得不同源的iframe之间可以进行消息通信。

  HTML5 通过引入源的感念对域安全进行了阐明和改进。源是网络上用来建立信任关系的地址的子集。源由规则(scheme)、主机(host)、端口(port)组成,例如由于scheme(https、http)不同,则源不同。

跨源通信通过 源来确定发送者,这就使得接收方可以忽略或者拒绝来自不可信源的消息。同时需要通过添加监听事件来接受消息,以避免被不可信应用程序的信息所干扰。但是在使用外来消息时,即便是可靠的数据源,也同样要谨慎,以防止内容注入。

在使用postMessage API时,需要遵循以下步骤:

1、检查浏览器是否支持

  1. if(typeof window.postMessage === undefined){
  2. //浏览器不支持postMessage
  3. }

2、发送消息

  1. window.postMessage("Hello","xx.example.com");

第一个参数包含要发送的数据,第二个参数时消息传递的目的地。

如果要发送消息给iframe,则使用如下代码:

  1. document.getElementById("iframe")[0].contentWindow.postMessage("Hello","xx.example.com");

3、监听消息事件

  1. window.addEventListener("message",messageHandler,true);
  2. var originWhiteList = ["a.example.com","b.example.com","c.example.com"];
  3. function messageHandler(e){
  4. if(checkWhiteList(e.origin)){
  5. processMessage(e.data);//发送方实际传送的消息
  6. }else{
  7. //忽略发送的消息
  8. }
  9. }
  10. function checkWhiteList(origin){
  11. for(var i = 0; i<originWhiteList.length; i++){
  12. if(origin === originWhiteList[i]){
  13. return true;
  14. }
  15. }
  16. return false;
  17. }

二、XMLHttpRequestLevel2

  XMLHttpRequestLevel2是XMLHttpRequest的改进版本,主要涉及:跨源XMLHttpRequess和进度事件(Progress events)。

  XMLHttpRequest仅限于同源通信,XMLHttpRequestLevel2通过跨资源共享实现(Cross Origin Resource Sharing)跨源XMLHttpRequests。

  在XMLHttpRequest中通过readystatechange事件来响应进度,但是其在某些浏览器中不被兼容。XMLHttpRequestLevel2用了一个有意义的名字Progress进度来命名进度事件。其进度事件的名称主要有loadstart、progress、abort、error、load、loadend。通过对程序属性设置回调函数,可以实现对这些事件的监听。

  在使用XMLHttpRequestLevel2时,需要遵循以下步骤:

1、检查浏览器是否支持

  1. var xhr = new XMLHttpRequest();
  2. if(typeof xhr.withXredentials === undefined){
  3. //浏览器不支持XMLHttpRequest
  4. }

2、构建跨源请求

  1. var crossOriginRequest = new XMLHttpRequest();
  2. crossOriginRequest.open("GET","http://www.example.com",true);

  在请求过程中,务必确保能够监听到错误,以找出出错原因,解决问题。

3、使用进度事件

  1. crossOriginRequest.onprogress = function(e){
  2. var total = e.total;
  3. var loaded = e.loaded;
  4. if(e.lengthComputable){
  5. //处理其他事情
  6. }
  7. }
  8. crossOriginRequest.upload..onprogress = function(e){
  9. var total = e.total;
  10. var loaded = e.loaded;
  11. if(e.lengthComputable){
  12. //处理其他事情
  13. }
  14. }

三、postMessage API示例应用

以跨源聊天应用为例,来演示门户页面和聊天部件之间的交互。

1、创建postMessagePortal.html页面

  1. <!DOCTYPE html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>跨源通信-WebChat</title>
  5. <link rel="stylesheet" href="styles.css">
  6. </head>
  7. <h1>跨源通信门户</h1>
  8. <p><b>源</b>: http://portal.example.com:8080</p>
  9. 状态 <input type="text" id="statusText" value="Online">
  10. <button id="sendButton">更改状态</button>
  11. <p>
  12. 使用postMessage发送一个状态,以更新包含在此页面中的widgetiframe。
  13. </p>
  14. <iframe id="widget" src="http://chat.example.net:8080/communication/postMessageWidget.html"></iframe>
  15. <script>
  16. var targetOrigin = "http://chat.example.net:8080";
  17. var notificationTimer = null;
  18. function messageHandler(e){
  19. if(e.origin == targetOrigin){
  20. notify(e.data);
  21. }else{
  22. //忽略
  23. }
  24. }
  25. function sendString(s){
  26. document.getElementById("widget").contentWindow.postMessage(s,targetOrigin);
  27. }
  28. function notify(message){
  29. alert(message);
  30. }
  31. function sendStatus(){
  32. var statusText = document.getElementById("statusText").value;
  33. sendString(statusText);
  34. }
  35. function loadDemo(){
  36. document.getElementById("sendButton").addEventListener("click",sendStatus,true);
  37. sendStatus();
  38. }
  39. window.addEventListener("load",loadDemo,true);
  40. window.addEventListener("message",messageHandler,true);
  41. </script>

2、创建postMessageWidget.html

  1. <!DOCTYPE html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>widget</title>
  5. <link rel="stylesheet" href="styles.css">
  6. </head>
  7. <h1>Widget iframe</h1>
  8. <p><b>源</b>: http://chat.example.net:8080</p>
  9. <p>通过门户设置状态为: <strong id="status"></strong> <p>
  10. <p>
  11. <input type="text" id="messageText" value="Widget notification.">
  12. <button id="actionButton">发送通知</button>
  13. </p>
  14. <script>
  15. var targetOrigin = "http://portal.example.com:8080";
  16. window.addEventListener("load",loadDemo,true);
  17. window.addEventListener("message",messageHandler,true);
  18. function loadDemo(){
  19. document.getElementById("actionButton").addEventListener("click",
  20. function() {
  21. var messageText = document.getElementById("messageText").value;
  22. sendString(messageText);
  23. }, true);
  24. }
  25. function messageHandler(e) {
  26. if (e.origin === "http://portal.example.com:8080") {
  27. document.getElementById("status").textContent = e.data;
  28. } else {
  29. // ignore messages from other origins
  30. }
  31. }
  32. function sendString(s) {
  33. window.top.postMessage(s, targetOrigin);
  34. }
  35. </script>

  注意:第一、上述的两个页面需要部署到web服务器;第二、两个页面必须来自不同的域。如果要在本机部署,则需要更改hosts文件,增加:

  1. 127.0.0.1 portal.example.com
  2. 127.0.0.1 chat.example.net

  修改完成后,需要关闭浏览器,再次重新打开。

四、XMLHttpRequestLevel2示例应用

  1、创建crossOriginUpload.html页面:

  1. <!DOCTYPE html>
  2. <head>
  3. header(“Access-Control-Allow-Origin: *”);
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <title>上传地理数据</title>
  6. <link rel="stylesheet" href="styles.css">
  7. </head>
  8. <script>
  9. function loadDemo() {
  10. var dataElement = document.getElementById("geodata");
  11. dataElement.textContent = JSON.stringify(geoData).replace(",", ", ", "g");
  12. var xhr = new XMLHttpRequest()
  13. if (typeof xhr.withCredentials === undefined) {
  14. document.getElementById("support").innerHTML = "浏览器不支持跨源XMLHttpRequest";
  15. } else {
  16. document.getElementById("support").innerHTML = "浏览器支持跨源XMLHttpRequest";
  17. }
  18. var targetLocation = "http://geodata.example.net:8080/upload";
  19. function setProgress(s) {
  20. document.getElementById("progress").innerHTML = s;
  21. }
  22. document.getElementById("sendButton").addEventListener("click",
  23. function() {
  24. xhr.upload.onprogress = function(e) {
  25. var ratio = e.loaded / e.total;
  26. setProgress("已上传" + ratio + "%");
  27. }
  28. xhr.onprogress = function(e) {
  29. var ratio = e.loaded / e.total;
  30. setProgress("已下载" + ratio + "%");
  31. }
  32. xhr.onload = function(e) {
  33. setProgress("完成");
  34. }
  35. xhr.onerror = function(e) {
  36. setProgress("错误");
  37. }
  38. xhr.open("POST", targetLocation, true);
  39. geoDataString = dataElement.textContent;
  40. xhr.send(geoDataString);
  41. }, true);
  42. }
  43. window.addEventListener("load", loadDemo, true);
  44. </script>
  45. <h1>XMLHttpRequest Level 2</h1>
  46. <p id="support"></p>
  47. <h4>上传地理数据:</h4>
  48. <textarea id="geodata">
  49. </textarea>
  50. </p>
  51. <button id="sendButton">上传</button>
  52. <script>
  53. geoData = [[39.080018000000003,
  54. 39.112557000000002,
  55. 39.135261,
  56. 39.150458,
  57. 39.170653000000001,
  58. 39.190128000000001,
  59. 39.204510999999997,
  60. 39.226759000000001,
  61. 39.238483000000002,
  62. 39.228154000000004,
  63. 39.249400000000001,
  64. 39.249533,
  65. 39.225276999999998,
  66. 39.191253000000003,
  67. 39.167993000000003,
  68. 39.145685999999998,
  69. 39.121620999999998,
  70. 39.095761000000003,
  71. 39.080593,
  72. 39.053131999999998,
  73. 39.02619,
  74. 39.002929000000002,
  75. 38.982886000000001,
  76. 38.954034999999998,
  77. 38.944926000000002,
  78. 38.919960000000003,
  79. 38.925261999999996,
  80. 38.934922999999998,
  81. 38.949373000000001,
  82. 38.950133999999998,
  83. 38.952649000000001,
  84. 38.969692000000002,
  85. 38.988512999999998,
  86. 39.010652,
  87. 39.033088999999997,
  88. 39.053493000000003,
  89. 39.072752999999999],
  90. [-120.15724399999999,
  91. -120.15818299999999,
  92. -120.15600400000001,
  93. -120.14564599999999,
  94. -120.141285,
  95. -120.10889900000001,
  96. -120.09528500000002,
  97. -120.077596,
  98. -120.045428,
  99. -120.0119,
  100. -119.98897100000002,
  101. -119.95124099999998,
  102. -119.93270099999998,
  103. -119.927131,
  104. -119.92685999999999,
  105. -119.92636200000001,
  106. -119.92844600000001,
  107. -119.911036,
  108. -119.942834,
  109. -119.94413000000002,
  110. -119.94555200000001,
  111. -119.95411000000001,
  112. -119.941327,
  113. -119.94605900000001,
  114. -119.97527599999999,
  115. -119.99445,
  116. -120.028998,
  117. -120.066335,
  118. -120.07867300000001,
  119. -120.089985,
  120. -120.112227,
  121. -120.09790700000001,
  122. -120.10881000000001,
  123. -120.116692,
  124. -120.117847,
  125. -120.11727899999998,
  126. -120.14398199999999]
  127. ];
  128. </script>
  129. <p>
  130. <b>状态: </b> <span id="progress">准备</span>
  131. </p>

  注意:部署web应用,运行crossOriginUpload.html页面时,可能会才出现如下的提示错误:

  这是因为访问一页面的域与所请求的域非同源造成的。且浏览器是根据响应头的规则来确定这个域是否同源可以接收。

  因此我们需要geodata.example.net:8080/upload在返回内容时,设置Header Access-Control-Allow-Origin,即:

  1.   Response.AddHeader("Access-Control-Allow-Origin","*") ;

  浏览器在接收到服务器返回信息时,会检查响应头的Access-Control-Allow-Origin,它的值标识请求内容所允许的域。如果将服务器设置Access-Control-Allow-Origin为*,表明该返回信息允许所有源访问。如果设置为具体的域,如xx.com,就表明除了同源外,只允许域来自xx.com的访问。

以上就是HTML5编程之旅-Communication技术初探的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行