HTML5 project Note 8: Use the HTML5 Cross-Domain Communication Mechanism for Data Synchronization

Source: Internet
Author: User

The Offline Application System is designed to operate our application system while the network is offline, and to interact with the server when the network is smooth.

Therefore, the Offline Application System will eventually become a client application similar to the C/S architecture.Program. Web application plug-ins Based on chrome or Safari are undoubtedly the best choice.

Taking Chrome Web application as an example, after the offline system is made into a web application, interaction with the server becomes the most troublesome thing, because offline web applications are installed on browsers of various users, the final server is just a fixed address provided by the terminal service provider. Therefore, this cross-origin communication occurs when a local browser initiates a request to the server.

For security reasons, JavaScript does not allow cross-origin calls to objects on other pages. Due to the restriction of the same-origin policy, JS under the domain name www.xx1.com cannot access and operate on objects under the domain name www.xx2.com.

The following is a description list of cross-origin access, which is taken from a blogArticle:

URL

Description

Allow communication?

Http://www.a.com/a.js
Http://www.a.com/ B .js

Under the same domain name

Allow

Http://www.a.com/lab/a.js
Http://www.a.com/script/ B .js

Different folders under the same domain name

Allow

Http://www.a.com: 8000/a. js
Http://www.a.com/ B .js

Different ports for the same domain name

Not Allowed

Http://www.a.com/a.js
Https://www.a.com/ B .js

Different protocols for the same domain name

Not Allowed

Http://www.a.com/a.js
Http: // 70.32.92.74/B. js

Corresponding IP addresses of domain names and domain names

Not Allowed

Http://www.a.com/a.js
Http://script.a.com/ B .js

The primary domain is the same and the subdomain is different.

Not Allowed

Http://www.a.com/a.js
Http://a.com/ B .js

Same domain name, different second-level domain names (same as above)

Not Allowed

(Cookie Access is not allowed in this case)

Http://www.cnblogs.com/a.js
Http://www.a.com/ B .js

Different domain names

Not Allowed

 

HTML5 provides a cross-document Message Mechanism, which enables communication across frames, tabs, or windows.

Postmessage API

Window. postmessage is a secure method for enabling cross-origin communication. Generally, scripts on different pages only allow mutual access and execution of their web pages. Window. postmessage provides a control mechanism to circumvent this restriction.

Browser support:

Browser type

Version Number

Chrome

Version 2.0 and later

Firefox

Version 3.0 and later

Internet Explorer

Version 8.0 and later

Opera

Version 9.6 and later

Safari

Version 4.0 and later

 

 

Data Sender:Otherwindow. postmessage (message, targetorigin );

Otherwindow

Reference to another window. Here, you can use the IFRAME element of the contentWindow attribute, or the object returned by window. Open, or use frames to name window. frames.

Message

Data sent to other windows.

Targetorigin

The destination address of the data transmission.

 

Data recipient:

Window. addeventlistener ("message", receivemessage, false );

Function receivemessage (Event)

{If (event. Origin! = "Http: // XXXX") return;

//...}

Event. Data

Obtain the Data Objects transmitted from other windows.

Event. Origin

The origin of the window when postmessage is sent. This string is the concatenation of the protocol and ": //", host name (if any), and ":" If a port, and the default port number of the given protocol.

Event. Source

A window establishes two-way communication between two windows from different sources, representing the window of your current receiver. You can use this object to send messages.

The information.htm page in our departure system stores information about the currently logged-on users. If the current network is online, our Save function needs to be synchronized to the server. In addition to saving, the information.htm page also provides cross-domain communication implementation.Code.

 

Similarly, we also need a server for cross-origin access, so we can create a server and design the database as follows:

This table is designed to save or modify the data submitted by the client relative to the data table on our client. Then we can write related operations on the server. The server also needs to create a page: crossdomain.htm, which serves as the source of cross-origin access (the source code of the attachment contains the server code ). On the crossdomain.htm page, write the program to process the value passed by the client.

The Code is as follows:

View code

 1     //  A listening event is added here to listen to the value passed by the client and process it.  2 Window. addeventlistener ("message", receivemessage, False  );  3           Function  Receivemessage (event ){  4   Saveuserinfo (event. Data, event. Source, event. origin );  5   } 6           7           //  Here is the processing program  8           //  We have made a web service here to take the JSON page form and save it.  9           //  Another step is to feedback the execution results. event. source refers to the sender's contentWindow,  10           //  Event. Origin indicates the sender's URL. In this way, the goal of sending feedback information to the source is achieved.  11           //  This method is called cross-origin communication. 12           Function  Saveuserinfo (userinfostr, source, origin ){  13   $. Ajax ({  14 Type: "Post" ,  15 Contenttype: "application/JSON; UTF-8" ,  16 URL: "WebService. asmx/postinformation" ,  17 Data: "{userinfostr: '" + userinfostr + "'}",  18 Datatype: 'json' ,  19 Anysc: False  ,  20 Success: Function  (Data ){  21                       If (Data. d = "1" ){  22 Source. postmessage ("saved successfully! " , Origin ); 23   }  24                       Else  {  25 Source. postmessage ("Saving failed! " , Origin );  26   }  27   }  28   });  29 }

 

Now let's write down the page for initiating a cross-domain request in our information.htm page.

First, we add an IFRAME element to link the page for cross-origin interaction. Then we get the contentWindow of the IFRAME and send the information as the source.

"Http: // 192.168.21.22: 86/crxserver/crossdomain.htm": assume that this address is the address of the webpage on our server. In this way, the data in the form is sent.

The Code is as follows:

View code

  1   function   crossdomain () {  2   var  userinfojson =  userinfo_serialy ();   3   var  ifrcrossdomain = document. getelementsbytagname ("iframe") [0 ]. contentWindow;   4   ifrcrossdomain. postmessage (userinfojson,   5  "http: // 192.168.21.22: 86/crxserver/crossdomain.htm ");   6  }  7  

After the server receives the form data, it processes the data. After processing, it sends the feedback to the sender (that is, the client where we initiate the request), and our sender receives the information, and handle it. Therefore, the sender also needs to add a listener event:

View code

 
1Window. addeventlistener ("message", receivemessage,False);2FunctionReceivemessage (event ){3 Alert (event. data );4}

Once the server returns data to us, we will output the data.

In this way, the process will come out:

After the file is submitted and saved, a dialog box is displayed, showing "saved successfully !", The data returned by the server is displayed, and the data is saved in the database.

 

About XMLHttpRequest Level 2

HTML5Defined inXMLHttpRequest Level 2It has two enhancements: Cross-origin communication and communication progress notification.(Progress events),If you are interested, you can find out:

Http://www.html5rocks.com/en/tutorials/file/xhr2/

 

Cross-origin in Chrome Web application (Chrome Web application plug-in:

{

"Name": "My extension ",

...

"Permissions ":[

"Http: // 192.168.21.22 /"

],

...

}

In this way, you can directly access the data on the server in the scripts in the plug-in. Of course, you need to set the security. These will be detailed in the Chrome Web Application Section.

 

Source code reference: crosscommunication

 

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.