HTML5 programming journey-Discussion on Communication technology-

Source: Internet
Author: User
This article mainly discusses two modules used to build real-time cross-source communication: Cross-document message communication (CrossDocumentMessaging) and XMLHttpRequestLevel2. Through these two modules, we can build Web applications for secure communication between different domains. This article mainly discusses two modules used to build real-time Cross-source communication: Cross Document Messaging and XMLHttpRequestLevel2. Through these two modules, we can build Web applications for secure communication between different domains.

1. Cross-document Message Communication

For the sake of security, communication between frames, tabs, and Windows running in the same browser has been severely restricted. However, in reality, there are still some reasonable requirements for the content of different sites to interact in the browser. Mashup is a typical example. It is a combination of different applications. To meet the above requirements, a new function is introduced: Cross-document message communication. It ensures secure cross-source communication between iframe, tabs, and windows.

The postMessage API is used to send messages. The sample code is as follows:

chatFrame.contentWindow.postMessage(content,url);

When receiving a message, you must add an event processing function on the page. When the message arrives, you can check the message source to determine how to process the message. The sample code is as follows:

Window. addEventListener ("message", messageHandler, true); function messageHandler (e) {switch (e. origin) {// indicates the data sending source case "friend.example.com": // process the message processMessage (e. data); // the break of the message actually sent by the sender; default: // other message sources // The message is ignored. }}

The postMessage API provides an interactive mode for communication between iframe of different sources.

HTML5 clarifies and improves domain security by introducing source concepts. The source is a subset of the addresses used to establish trust relationships on the network. The source consists of rules (scheme), host (host), and port (port). For example, the source is different because scheme (https, http) is different.

Cross-source communication determines the sender through the source, so that the receiver can ignore or reject messages from non-source sources. At the same time, you need to add listening events to receive messages to avoid being disturbed by information of untrusted applications. However, when using external messages, even reliable data sources should also be cautious to prevent content injection.

To use the postMessage API, follow these steps:

1. Check whether the browser supports

If (typeof window. postMessage === undefined) {// the browser does not support postMessage}

2. Send messages

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

The first parameter contains the data to be sent, and the second parameter indicates the destination of the message.

If you want to send a message to iframe, use the following code:

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

3. Listen to message events

Window. addEventListener ("message", messageHandler, true); var originWhiteList = ["a.example.com", "B .example.com", "c.example.com"]; function messageHandler (e) {if (checkWhiteList (e. origin) {processMessage (e. data); // The message actually sent by the sender} else {// ignore the sent message} function checkWhiteList (origin) {for (var I = 0; I
 
  
Ii. XMLHttpRequestLevel2
  

XMLHttpRequestLevel2 is an improved version of XMLHttpRequest. It mainly involves cross-source XMLHttpRequess and Progress events (Progress events ).

XMLHttpRequest is only applicable to same-source communication. XMLHttpRequestLevel2 implements Cross-source XMLHttpRequests through Cross-Origin Resource Sharing.

In XMLHttpRequest, The readystatechange event is used to respond to the progress, but it is not compatible in Some browsers. XMLHttpRequestLevel2 uses a meaningful name Progress to name a Progress event. The progress events include loadstart, progress, abort, error, load, and loadend. You can monitor these events by setting callback functions for program properties.

Follow these steps when using XMLHttpRequestLevel2:

1. Check whether the browser supports

Var xhr = new XMLHttpRequest (); if (typeof xhr. withXredentials === undefined) {// the browser does not support XMLHttpRequest}

2. build cross-source requests

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

During the request process, ensure that errors are monitored to identify the cause of the error and solve the problem.

3. Use progress events

CrossOriginRequest. onprogress = function (e) {var total = e. total; var loaded = e. loaded; if (e. lengthComputable) {// handle other things} crossOriginRequest. upload .. onprogress = function (e) {var total = e. total; var loaded = e. loaded; if (e. lengthComputable) {// handle other things }}
3. postMessage API example application

The cross-source chat application is used as an example to demonstrate the interaction between the portal page and chat components.

Create a postmessageportal.html page in 1 、

               
       Cross-source communication-WebChat    
       Cross-source communication portal

Source: Http://portal.example.com: 8080

Status Change status

Use postMessage to send a status to update the widgetiframe contained on this page.

Script var targetOrigin = "http://chat.example.net: 8080"; var icationicationtimer = null; function messageHandler (e) {if (e. origin = targetOrigin) {policy (e. data);} else {// ignore} function sendString (s) {document. getElementById ("widget "). contentWindow. postMessage (s, targetOrigin);} function specified y (message) {alert (message);} function sendStatus () {var statusText = document. getElementById ("statusText "). value; sendString (statusText);} function loadDemo () {document. getElementById ("sendButton "). addEventListener ("click", sendStatus, true); sendStatus ();} window. addEventListener ("load", loadDemo, true); window. addEventListener ("message", messageHandler, true); script

Create postmessagewidget.html

           
       Widget    
       Widget iframe

Source: Http://chat.example.net: 8080

Set the status through the portal:

Send notification

Script var targetOrigin = "http://portal.example.com: 8080"; window. addEventListener ("load", loadDemo, true); window. addEventListener ("message", messageHandler, true); function loadDemo () {document. getElementById ("actionButton "). addEventListener ("click", function () {var messageText = document. getElementById ("messageText "). value; sendString (messageText) ;}, true) ;}function messageHandler (e) {if (e. origin = "http://portal.example.com: 8080") {document. getElementById ("status "). textContent = e. data;} else {// ignore messages from other origins} function sendString (s) {window. top. postMessage (s, targetOrigin);} script

Note: first, the two pages must be deployed on the web server. Second, the two pages must come from different domains. If you want to deploy on the local machine, you need to change the hosts file and add:

127.0.0.1 portal.example.com127.0.0.1 chat.example.net

After the modification, you need to close the browser and open it again.

4. XMLHttpRequestLevel2 example application

1 create crossoriginupload.html page:

Header ("Access-Control-Allow-Origin :*");
   Upload Geographic Data
   Script function loadDemo () {var dataElement = document. getElementById ("geodata"); dataElement. textContent = JSON. stringify (geoData ). replace ("," g "); var xhr = new XMLHttpRequest () if (typeof xhr. withCredentials === undefined) {document. getElementById ("support "). innerHTML = "the browser does not support cross-source XMLHttpRequest";} else {document. getElementById ("support "). innerHTML = "the browser supports cross-source XMLHttpRequest";} var targetLocation =" http://geodata.example.net:8080/upload "; Function setProgress (s) {document. getElementById ("progress "). innerHTML = s;} document. getElementById ("sendButton "). addEventListener ("click", function () {xhr. upload. onprogress = function (e) {var ratio = e. loaded/e. total; setProgress ("uploaded" + ratio + "%");} xhr. onprogress = function (e) {var ratio = e. loaded/e. total; setProgress ("downloaded" + ratio + "%");} xhr. onload = function (e) {setProgress ("finished");} xhr. onerror = function (e) {setProgress ("error");} xhr. open ("POST", targetLocation, true); geoDataString = dataElement. textContent; xhr. send (geoDataString) ;}, true) ;}window. addEventListener ("load", loadDemo, true); script XMLHttpRequest Level 2

Upload geographic data:

UploadScript geoData = [[39.080018000000003, 39.112557000000002, 39.135261, 39.150458, 39.170653000000001, 39.190128000000001, 39.204510999999997, 39.226759000000001, 39.238483000000002, 39.228154000000004, 39.249400000000001, 39.249533, 39.225276999999998, 39.191253000000003, 39.167993000000003, 39.145685999999998, 39.121620999999998, 39.095761000000003, 39.080593, 39.053131999999998, 39.02619, 39.002929000000002, 38.982886000000001, 38.954034999999998, 38.944926000000002, 38.919960000000003, 38.925261999999996, 38.934922999999998, 38.949373000000001, 38.950133999999998, 38.952649000000001, 38.969692000000002, 38.988512999999998, 39.010652, 39.033088999999997, 39.053493000000003, 39.072752999999999], [-120.15724399999999,-120.15818299999999,-120.15600400000001,-120.14564599999999,-120.141285,-120.10889900000001,-120.09528500000002,-120.077596,-120.045428,-120.0119,-119.98897100000002,-119.95124099999998, -119.93270099999998,-119.927131,-119.92685999999999,-119.92636200000001,-119.92844600000001,-119.911036,-119.942834,-119.94413000000002,-119.94555200000001,-119.95411000000001,-119.941327,-119.94605900000001,-119.97527599999999, -119.99445,-120.028998,-120.066335,-120.07867300000001,-120.089985,-120.112227,-120.09790700000001,-120.10881000000001,-120.116692,-120.117847,-120.11727899999998]; script

Status:Preparation

Note: When deploying webapplications and running the crossoriginupload.html page, the following error may occur:

The above is the preliminary study of the Communication Technology for HTML5 programming. For more information, see PHP Chinese Network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.