Explain the basic usage of communication API in HTML5

Time:2021-10-25

1. Cross document message communication
Cross document message communication can ensure safe cross source communication among iframe, tab and window. It defines the PostMessage API as the standard way to send messages. Sending a message using PostMessage is very simple. 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 handler 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 delivered by the sender, and the origin attribute is the sending source.
The PostMessage API is not only competent for the communication between homologous documents, but also useful when the browser does not allow non homologous communication. In view of its consistency and ease of use, PostMessage is also recommended for communication between homologous documents. The PostMessage API should always be used in communication in a JavaScript environment, such as when communicating with HTML5 web worker.
1.1 understanding source safety
HTML5 introduces the concept of origin to clarify and improve domain security. A source is a subset of addresses used to establish trust relationships on the network. The source consists of scheme, host and post.
Path is not considered in the concept of source.
HTML5 defines the serialization of the source. Sources appear as strings in APIs and protocols.
The security rules of PostMessage ensure that messages are not delivered to unexpected source pages. When sending a message, the sender determines 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 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 white list and tell the browser to only process messages from trustworthy sources.
It is best never to evaluate strings from third parties. Furthermore, avoid using the eval method to handle application internal strings. JSON can be used through the window. JSON or JSON. Org parser.
1.2 browser support for cross document message communication
A common method is to detect whether the withcredentials attribute exists in the XMLHttpRequest object:

JavaScript CodeCopy contents to clipboard
  1.   var xhr = new XMLHttpRequest(); if (typeof xhr.withCredentials === undefined) { //Cross source XMLHttpRequest is not supported  }  else   {  // Supports cross source XMLHttpRequest  }  

1.3 using the PostMessage API
Tip: the messageevent interface defined by HTML5 is also part of HTML5 WebSockets and HTML5 webworkers. The communication function of HTML5 uses the API for receiving messages, which is consistent with the messageevent interface. Other communication APIs, such as eventsource API and web workers, also use the messageevent interface to deliver messages.
1.4 creating applications using the PostMessage API
send 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 contents to clipboard
  1. window.postMessage(“Hello, world”“porta”);  

The first parameter includes the data to be sent, and the second parameter is the destination of the message transmission. To send the message to iframe, you can call postMessage in the corresponding iframe contentWindow. The code is as follows:
  

JavaScript CodeCopy contents to clipboard
  1. document.getElementsByTagName(“iframe”)[0].contentWindow.postMessage(“Hello, world”“cha”);  

Listen for message events
When receiving a message, you only need to add an event handler function to the page. When a message arrives, it is determined whether to process the message by checking the source of the message.
  

JavaScript CodeCopy contents 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.
A source consists of a scheme, a host, and a port.
For example, due to different rules (such as HTTPS and HTTP), the source of the page is different from that of the page.
Path is not considered in the concept of source. For example, different from the path, they are the same source.
Sources appear as strings in APIs and protocols.
  

JavaScript CodeCopy contents to clipboard
  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  } }  

The PostMessage API can be used for homologous and non homologous communication. In view of its consistency, it is also recommended to apply PostMessage when communicating between homologous documents.
2 XMLHttpRequest Level2
As an improved version of XMLHttpRequest, XMLHttpRequest level2 has been greatly improved in function. It mainly focuses on two aspects:
(1) Cross source xmlhttprequests;
(2) Progress events
2.1 cross source xmlhttprequst
Xmlhttprequestlevel2 implements cross source xmlhttprequests through CORS (cross origin resource sharing).
The cross source HTTP request includes an origin header, which provides the server with the source information of the HTTP request. The header is protected by the browser and cannot be modified by the application code. In essence, it has the same function as the origin attribute of message events in cross document message communication.
The CORS specification requires that some sensitive behaviors, such as requests for certificates or options preflight requests other than get and post, must be sent by the browser to the server to determine whether such behaviors can be supported and allowed, which means that behind successful communication, servers with CORS capabilities may need to support them.
2.2 progress events
One of the most important API improvements in the new version of XMLHttpRequest is the increased response to progress.
XMLHttpRequest level2 uses a meaningful name progress to name progress events.
3 advanced functions
3.1 structured data
Previous versions of PostMessage only supported strings. Later versions supported other data types such as JavaScript objects, canvas imagedata, and files. Because different browsers support different specifications, the support for different object types is also different.
3.2 Framebusting
Framebuilding technology can be used to ensure that some content is not loaded into JFrame. The application program first checks whether the window is the outermost window (window. Top). If not, it jumps out of the frame containing it. The code is as follows:

JavaScript CodeCopy contents 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. The level 2 specification supports calling the send () method to send blob and arraybuffer objects
  

XML/HTML CodeCopy contents 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 property value to text, document, arraybuffer, or blob to control the object type returned with the response property. If you want to view the original bytes contained in the HTTP response body, you need to set the value of the responsetyper property to arraybuffer or blob.