Describes the basic usage of the Communication API in html5.

Source: Internet
Author: User

Describes the basic usage of the Communication API in html5.
1. Cross-document Message Communication
Cross-document message communication ensures secure cross-source communication between iframe, tabs, and windows. It defines the postMessage API as the standard method for sending messages. Sending messages using postMessage is very simple, and the code is as follows:
ChatFrame. contextWindow. postMessage ('hello, world', 'HTTP: // www.example.com ');
When receiving a message, you only need to add an event processing function on the page. When a message arrives, check the message source to determine whether to process the message.
A message event is a DOM event with data and origin attributes. The data attribute is the actual message transmitted by the sender, and the origin attribute is the sending source.
PostMessage API is not only competent for communication between same-source documents, but also useful when the browser does not allow non-same-source communication. In view of its consistency and ease of use, postMessage is also recommended for communication between source documents. PostMessage API should always be used for communication in the JavaScript environment, for example, when using HTML5 Web Worker for communication.
1.1 understand source security
HTML5 glory introduces the origin concept to clarify and improve domain security. The source is a subset of addresses used to establish trust relationships on the network. The source consists of a rule (scheme), a host (host), and a port (post.
Paths are not considered in the concept of source.
HTML5 defines source serialization. The source appears as a string in APIs and protocols.
PostMessage security rules ensure that messages are not transmitted to unexpected source pages. When a message is sent, the sender specifies the source of the receiver. If the window used by the sender to call postMessage does not have a specific source (for example, the user jumps to another site), the browser will not send the message.
Similarly, when receiving a message, the sender's source is also part of the message. To avoid forgery, the message source is provided by the browser. The receiver can decide which messages to process and which messages to ignore. We can keep a whitelist to tell the browser to process only the messages that can be sent from the source.
It is best never to evaluate a string from a third party. Furthermore, avoid using the eval method to process internal strings of the application. You can use JSON In the window. json or JSON or. org parser.
1.2 cross-document message communication browser support
A common practice is to check whether the withCredentials attribute exists in the XMLHttpRequest object:
Copy the content to the clipboard using JavaScript Code

  1. Var xhr = new XMLHttpRequest (); if (typeof xhr. withCredentials === undefined) {// cross-source XMLHttpRequest} else {// cross-source XMLHttpRequest} is supported}
1.3 Use postMessage API
The MessageEvent interface defined by HTML5 is also part of HTML5 WebSockets and HTML5 WebWorkers. The communication function of HTML5 is consistent with the MessageEvent interface. Other communication APIs, such as the EventSource API and Web Workers, use the MessageEvent API to transmit messages.
1.4 Use the postMessage API to create an application
Send message
You can call the postMessage () function in the window object of the target page to send messages. The Code is as follows:
Copy the content to the clipboard using JavaScript Code
  1. Window. postMessage ("Hello, world", "porta ");
The first parameter includes the data to be sent, and the second parameter is the destination of message transmission. To send a message to iframe, you can call postMessage in the contentWindow of the iframe. The Code is as follows:
Copy the content to the clipboard using JavaScript Code
  1. Document. getElementsByTagName ("iframe") [0]. contentWindow. postMessage ("Hello, world", "cha ");
Listen to message events
When receiving a message, you only need to add an event processing function to the page. When a message arrives, check the message source to determine whether to process the message.
Copy the content to the clipboard using JavaScript Code
  1. Window. postMessage ("Hello, world", "porta ");
A message event is a DOM event with data and origin attributes. The data attribute is the actual message transmitted by the sender, and the origin attribute is the sending source.
The source consists of a rule (scheme), a host (host), and a port (port.
For example, because the rules are different (such as https and http), the page source is different from the page source.
Paths are not considered in the concept of source. For example, different paths are the same source.
The source appears as a string in APIs and protocols.
Copy the content to the clipboard using JavaScript Code
  1. Var originWhiteList = ["porta", "game", ""]; function checkWhiteList (origin) {for (var I = 0; I <originWhiteList. length; I ++) {if (origin = originWhiteList [I]) {return true ;}} return false ;} function messageHandler (e) {if (checkWhiteList (e. origin) {processMessage (e. data);} else {// ignore messages from unknown sources }}
PostMessage API can be used for communication between the same source and non-same source. In view of its consistency, postMessage is also recommended for communication between the same source and non-same source documents.
2 XMLHttpRequest Level2
As the release version of XMLHttpRequest, XMLHttpRequest Level2 has greatly improved its functionality. It mainly focuses on two aspects:
(1) Cross-source XMLHttpRequests;
(2) Progress events (Progress events)
2.1 cross-source XMLHttpRequst
XMLHttpRequestLevel2 implements Cross-source XMLHttpRequests through CORS (Cross Origin Resource Sharing.
A cross-Origin HTTP request includes an Origin header that provides the Origin information of the HTTP request to the server. The header is protected by a browser and cannot be modified by application code. Essentially, it works the same as the origin attribute of message events in cross-document message communication.
CORS specifications require that browser requests must be sent to the server for sensitive behaviors, such as requests for certificate applications or preflight requests other than GET and POST requests, to determine whether such behavior can be supported and permitted, this means that successful communication may be supported by servers with CORS capabilities.
2.2 progress events
One of the most important API improvements in the new XMLHttpRequest version is to increase the response to the progress.
XMLHttpRequest Level2 uses a meaningful name Progress to name a Progress event.
3. Advanced functions
3.1 structured data
Earlier versions of postMessage only support strings. Later versions support JavaScript objects, canvas imageData, files, and other data types. Because different browsers have different support for specifications, the support for different object types is also different.
3.2 Framebusting
Framebusting technology can be used to ensure that some content is not loaded into jframe. The application first checks whether the window in which it is located is the window of the outermost layer (window. top). If not, it skips the framework that contains it. The Code is as follows:
Copy the content to the clipboard using JavaScript Code
  1. If (window! = Window. top)
  2. {
  3. Window. top. location = location;
  4. }
3.3 binary data
Browsers that support new binary APIs (such as Typed Array) can use XMLHttpRequest to send binary data. Level 2 specifications support calling the send () method to send Blob and ArrayBuffer objects
Copy XML/HTML Code to clipboard
  1. Var a = new Uint8Array ([8, 6, 7, 5, 3, 0, 9]); var xhr = new XMLHttpRequest (); xhr. open ("POST", "/data/", true); console. log (a); xhr. send (. buffer );
XMLHttpRequest Level 2 also exposes binary response data. Set the responseType attribute value to text, document, arraybuffer, or blob to control the object type returned by the response attribute. To view the original bytes contained in the HTTP response body, set the responseTyper attribute value to arraybuffer or blob.

Related Article

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.