This article mainly introduces the basic usage methods of Communication API in HTML5. The article involves two important modules for building real-time and cross-domain communication: cross-document message communication and XMLHttpRequest Level 2. Friends who need it can refer to the following 1. Cross-document message communication
Cross-document message communication can ensure that cross-origin communication is securely conducted 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, you only need to add an event handling function to the page. When a message arrives, it is determined whether to process the message by checking the source of the message.
A message event is a DOM event with data and origin attributes. The data attribute is the actual message passed by the sender, while the origin attribute is the sending source.
The postMessage API is not only capable of communication between homologous documents, but also is also useful when the browser does not allow non-homologous communication. Given its consistency and ease of use, postMessage is also recommended when communicating between homologous documents. The postMessage API should always be used in communications in JavaScript environments, such as when using HTML5 Web Worker communications.
1.1 Understand source securityThe concept of HTML5 glory introduction source (origin) has clarified and improved domain security. Source is a subset of addresses used to establish trust relationships on the network. The source consists of a rule, a host, and a port.
The concept of source does not consider paths.
HTML5 defines the serialization of the source. Sources appear as strings in APIs and protocols.
The security rules for postMessage ensure that messages are not delivered to unexpected source pages. When sending a message, the sender defines the source of the receiver. If the window sent to call postMessage does not have a specific source (for example, the user jumps to another site), the browser will not send messages.
Similarly, when receiving a message, the sender's source is also used as 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 that tells the browser to process messages only from trusted sources.
It is best not to evaluate strings from third parties. Furthermore, avoid using the eval method to process the application internal strings. You can use JSON through window.JSON or json, .org parsers.
1.2 Browser support for cross-document message communicationA common practice is to detect whether the withCredentials property exists in the XMLHttpRequest object:
JavaScript Code Copy content to clipboard