Home > Web Front-end > H5 Tutorial > body text

Detailed explanation of the basic usage of Communication API in HTML5_html5 tutorial skills

WBOY
Release: 2016-05-16 15:45:55
Original
1612 people have browsed it
1. Cross-document message communication
Cross-document message communication can ensure safe cross-source communication between iframes, tabs, and windows. It defines the postMessage API as the standard way to send messages. It is very simple to use postMessage to send messages. The code is as follows:
chatFrame.contextWindow.postMessage('Hello,world','http://www.example.com');
When receiving messages, just click on the page Add an event handling function. When a message arrives, the source of the message is checked to determine whether to process the message.
The message event is a DOM event with data and origin attributes. The data attribute is the actual message delivered by the sender, and the origin attribute is the sending source.
The postMessage API is not only capable of communicating between documents of the same origin, but it is also useful when the browser does not allow non-original communication. Due to its consistency and ease of use, postMessage is also recommended when communicating between documents of the same origin. The postMessage API should always be used when communicating in a JavaScript environment, such as when communicating with HTML5 Web Workers.
1.1 Understanding origin security
HTML5 Rongguang introduces the concept of origin to clarify and improve domain security. An origin is a subset of addresses used to establish trust relationships on the network. The source consists of rules (scheme), host (host), and port (post).
Path is not considered in the concept of source.
HTML5 defines serialization of sources. Sources appear as strings in APIs and protocols.
PostMessage security rules ensure that messages are not delivered to unintended source pages. When sending a message, it is the sender who specifies the source of the receiver. If the window used by the sender to call postMessage does not have a specific origin (for example, the user jumped to another site), the browser will not deliver the message.
Similarly, when receiving a message, the sender's source is also included as part of the message. To avoid forgery, the source of the message is provided by the browser. The receiver can decide which messages to process and which to ignore. We can keep a whitelist and tell the browser to only process messages from trusted sources.
It is best to never evaluate strings from third parties. Furthermore, avoid using the eval method to process application-internal strings. JSON can be consumed via window.JSON or json,.org parsers.
1.2 Browser support for cross-document message communication
A common approach is to detect whether the withCredentials attribute exists in the XMLHttpRequest object:
JavaScript CodeCopy content to clipboard
  1.  var xhr = new XMLHttpRequest(); if (typeof xhr.withCredentials === undefined) { //Does not support cross-origin XMLHttpRequest } else { //Supports cross-origin XMLHttpRequest }
1.3 Using postMessage API
Tips The MessageEvent interface defined by HTML5 is also part of HTML5 WebSockets and HTML5 WebWorkers. The communication function of HTML5 uses the same API for receiving messages as the MessageEvent interface. Other communication APIs, such as EventSource API and Web Workers, also use the MessageEvent interface to deliver messages.
1.4 Create an application using postMessage API
Send a message
You can send a message by calling the postMessage() function in the window object of the target page. The code is as follows:
JavaScript CodeCopy content to clipboard
  1. window.postMessage("Hello, world", "porta");
The first parameter contains the data to be sent, and the second parameter is the destination of the message. To send a message to an iframe, you can call postMessage in the contentWindow of the corresponding iframe. The code is as follows:
JavaScript CodeCopy content to clipboard
  1. document.getElementsByTagName("iframe")[0].contentWindow.postMessage("Hello, world", "cha");
Listening to message events
When receiving messages, you only need to add an event handler to the page. When a message arrives, the source of the message is checked to determine whether to process the message.
JavaScript CodeCopy content to clipboard
  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 delivered by the sender, and the origin attribute is the sending source.
The source consists of rule (scheme), host (host), and port (port).
For example: due to different rules (such as https and http), the source of the page is different.
The path is not considered in the concept of source. For example: instead of just paths, they are the same source.
Sources appear as strings in APIs and protocols.
JavaScript CodeCopy content to clipboard
  1. var originWhiteList = ["porta", "game" , ""]; function checkWhiteList(origin) { for (var i=0; iif (origin === originWhiteList[i]) { return true; } } return false; } function messageHandler(e) { if (checkWhiteList(e.origin)) { processMessage(e. data); } else { //Ignore messages from unknown sources } }
The postMessage API can be applied to both same-origin and non-original communication. In view of its consistency, postMessage is also recommended when communicating between homologous documents.
2 XMLHttpRequest Level2
As an improved version of XMLHttpRequest, XMLHttpRequest Level2 has greatly improved its functionality. Mainly focused on two aspects:
(1) Cross-source XMLHttpRequests; Origin Resource Sharing (cross-origin resource sharing) implements cross-origin XMLHttpRequests.
Cross-origin HTTP requests include an Origin header to provide the server with source information of the HTTP request. The header is protected by the browser and cannot be modified by application code. Essentially, it has the same effect as the origin attribute of a message event in cross-document message communication.
CORS specification requires that some sensitive behaviors, such as requests to apply for certificates or OPTIONS preflight requests other than GET and POST, must be sent by the browser to the server to determine whether this behavior can be supported. and permission, which means that successful communication may need to be supported by a server with CORS capabilities.
2.2 Progress Events

One of the most important API improvements in the new version of XMLHttpRequest is the addition of response to progress.
XMLHttpRequest Level2 uses a meaningful name Progress to name the progress event.
3 Advanced functions
3.1 Structured data

Early versions of postMessage only support strings. Later versions supported other data types such as JavaScript objects, canvas imageData, and files. Due to differences in specification support between different browsers, support for different object types is also different.
3.2 Framebusting

Framebusting technology can be used to ensure that certain content is not loaded into jframe. The application first detects whether the window it is in is the outermost window (window.top). If not, it jumps out of the frame containing it. The code is as follows:


JavaScript Code

Copy content to clipboard
  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 specification supports calling the send() method to send Blob and ArrayBuffer objects
 
XML/HTML CodeCopy content 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(a.buffer);
XMLHttpRequest Level 2 also exposes binary response data. Set the responseType attribute value to text, document, arraybuffer, or blob to control the type of object returned by the response attribute. If you want to view the raw bytes contained in the HTTP response body, you need to set the responseTyper attribute value to arraybuffer or blob.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template