HTML5 postMessage and onmessage API Details Application, html5postmessage

Source: Internet
Author: User
Tags sessionstorage

HTML5 postMessage and onmessage API Details Application, html5postmessage

With the development of HTML5, it is very important to understand and familiarize yourself with HTML5 API interfaces. PostMessage (send) and onmessage APIs are widely used in html5. for example, Web Workers can use these APIs to call JavaScript between multiple threads, cross-document messaging implements JavaScript calling between two different domains. This topic describes the detailed application of this group of APIs in Web Workers, Cross-document messaging, WebSockets, and Server-Sent Events.

By 2008, W3C had developed the first HTML5 draft. HTML5 has carried more and more new features and functions. It not only enhances the performance of the Web system or Web page, but also adds support for Web application functions such as local databases. Among them, the most important one is the support for multithreading. In HTML5, the concept of Web Workers is proposed, and three main features of Web Workers are standardized: long running (response ), ideal Startup Performance and memory consumption. Web Workers allows developers to write background programs that can run for a long time without being interrupted by users, execute transactions or logic, and ensure that pages respond to users in a timely manner.

 

Is the Cookie swollen?

 

Cookie defects are obvious.

1. data size: as a storage container, the cookie size is limited to around 4 kb, which is very difficult, especially for the complex business logic requirements, the size of 4 kb Not only stores some configuration fields but also simple single-value information. For most developers, I really don't know what to expect.

2. Security: Because the cookie in the HTTP request is transmitted in plain text (HTTPS is not), the security problem is still very high.

3. network burden: We know that cookies will be appended to each HTTP request and will be transmitted in the HttpRequest and HttpResponse headers. Therefore, unnecessary traffic loss is added.

 

Introduction to Web WorkersWeb Workers

Web Workers provides a method for running scripts on Web Front-end Web pages in background processes. Once it is created, Web Workers can send a task request to the task pool through postMessage, and then return the message to the event handler specified by the creator through postMessage after execution (capture through onmessage ). The Web Workers process can process tasks without affecting the user interface. In addition, it can also use XMLHttpRequest to process I/O, but generally, background processes (including Web Workers processes) DOM cannot be operated. If you want the result processed by the background program to change the DOM, you can only process it by returning the message to the callback function of the Creator.

For more information about HTML5 browser support, refer to the website When can I use...

Use postMessage and onmessage in Web Workers

First, you need to create a new Worker instance in the JavaScript code on the client page. The parameter is the name of the JavaScript file to be run in another thread. Then listen to the onmessage event on this instance. Finally, JavaScript in the other thread can pass data between the two threads by calling the postMessage method.

List 1. Create a Worker instance in the main thread and listen to onmessage events
<Html> 

 

In the client's compute. js, the result is simply returned to the main thread through the postMessage method after repeated addition operations. The purpose is to wait for a while. During this period, the main thread should not be blocked. You can drag and drop the browser to expand or narrow the browser window and perform other operations to test this phenomenon. The result of this non-blocking main thread is what the Web Workers wants to achieve.

Listing 2. Calling the postMessage method in compute. js returns the calculation result
Var I = 0; function timedCount () {for (var j = 0, sum = 0; j <100; j ++) {for (var I = 0; I <100000000; I ++) {sum + = I ;}// call postMessage to send the message postMessage (sum);} postMessage ("Before computing, "+ new Date (); timedCount (); postMessage (" After computing, "+ new Date ());

 

Figure 1. Running results in the browser

Introduction to Cross-document messagingCross-document messaging

Due to the restriction of the same-origin policy, JavaScript cross-origin is always a tough issue. HTML5 provides the ability to receive and send information between webpage documents. To use this function, you only need to obtain the instance of the window object in which the webpage is located, and not only the Web pages with the same origin (domain + port number) can communicate with each other, but can even implement cross-origin communication. To receive information sent from other windows, you must listen to the onmessage event of the window object. Other windows can transmit data through the postMessage method. This method uses two parameters: the first parameter is the message text sent, but it can also be any JavaScript Object (converted to text through JSON ), the second parameter is the URL address of the message receiving Object window. You can use the wildcard '*' in the URL string to specify all locations.

Use postMessage and onmessage in Cross-document messaging

To achieve communication between different domains, you need to add two domain names to the hosts file of the operating system for simulation.

Listing 3. Adding two different domain names to the hosts file
 127.0.0.1  parent.com  127.0.0.1  child.com

Embed the child page in the parent page through iframe, and call the postMessage method in JavaScript code to send data to the Child Window.

Listing 4. embed a child page in the parent page and call the postMessage method to send data
<Html> 

 

Listen to the onmessage event in the subwindow and use JavaScript to display the data sent from the parent window.

Listing 5. Listening for onmessage events in the subwindow, displaying the data sent from the parent window
<Html> Connect: function () {var location = "ws: // localhost: 8000/"; // create WebSockets and input the WebSockets server address this. _ ws = new WebSocket (location); this. _ ws. onmessage = this. _ onmessage; // WebSockets also provides onopen and onclose events this. _ ws. onopen = this. _ onopen; this. _ ws. onclose = this. _ onclose ;}

 

In the _ onmessage method, receive data and display it on the page

Listing 7. _ onmessage Method
_ Onmessage: function (event) {// The event parameter has the data attribute, that is, the data if (event. data) {var messageBox = document. getElementById ('messagebox'); var spanText = document. createElement ('span '); spanText. className = 'text'; // display the data sent from the server in the spanText window. innerHTML = event. data; var lineBreak = document. createElement ('br '); messageBox. appendChild (spanText); messageBox. appendChild (lineBreak); messageBox. scrollTop = messageBox. scrollHeight-messageBox. clientHeight ;}},

 

In the _ onopen method, call the _ send method to send a message to the server, and the connection has been established. In the _ onclose method, set the WebSocket instance to null to release the resource.

Listing 8. _ onopen, _ onclose, and send Methods
_ Onopen: function () {server. _ send ("Client: Open WebSockets," + new Date () ;}, // The message parameter is the data sent from the Client to the server. _ send: function (message) {if (this. _ ws) this. _ ws. send (message) ;}, // This method provides external code to call send: function (text) {if (text! = Null & text. length> 0) server. _ send (text) ;}, _ onclose: function (m) {this. _ ws = null ;}

 

Encapsulate these methods in a server object to facilitate external calls. You only need to call the connect Method of the server to establish a connection, and then call the send method to send data.

Listing 9. encapsulate client implementation
Var server ={// connect and send methods are mainly provided externally: function (){...}, _ onopen: function (){...}, _ send: function (message ){...}, send: function (text ){...}, _ onmessage: function (event ){...}, _ onclose: function (m ){...}};

 

On the server side, simply modify the echo-server.js example provided in WebSocket-Node through the JavaScript language. Only the key code is shown here. For other code, see the WebSocket-Node example.

Listing 10. Simple WebSockets server implementation
// Listen to the client's connection request wsServer. on ('connect ', function (connection) {function sendCallback (err) {if (err) console. error ("send () error:" + err);} // listen to the connection request sent by the client. on ('message', function (message) {if (message. type = 'utf8') {// specifies whether the client sends data of the text or binary type connection. sendUTF ("Server: Get message: <br/>" + message. utf8Data, sendCallback);} else if (message. type = 'binary ') {connection. sendBytes (message. binaryData, sendCallback) ;}}); connection. on ('close', function (reasonCode, description ){});});

 

Figure 4. Click Connect

Figure 5. Enter the content and click Send Message.

Introduction to Server-Sent EventsServer-Sent Events

The HTML5 Server-Sent event model allows you to push real-time data from the Server to the browser. This article describes how to use the Eventsource object to process and receive and send data between pages. On the client side, we use HTML5 + JavaScript, and the server side uses Java. In the existing Ajax mode, the web page continuously requests the server to transmit new data, and the client is responsible for requesting data. In the server sending mode, the server pushes updates instead of executing continuous data requests in the client code. Once you initialize the Server-Sent event on the page, the Server script continuously sends updates. Once the client JavaScript code receives an update, it will display the new data written to the page.

Use onmessage in Server-Sent Events

Server-Sent Events and WebSockets are the same. WebSockets implements two-way communication between the Server and the client, while Server-Sent Events only refers to one-way communication between the Server and the client, server-Sent Events also requires Server implementation. This article uses Java-based Servlet technology to implement Server. For the format of data written from the Server to the client, refer to the W3C standard Document Server-Sent Events about Server-Sent Events. Because it is one-way communication between the Server and the client, there is no postMessage method in Server-Sent Events.

First, the client uses the JavaScript code to create an EventSource instance. The parameter is the URL address of the EventSource server. Then, listen to the onmessage event on this instance to receive the data sent by the server.

Listing 11. Create an EventSource object and listen to the onmessage event
If (!! Window. eventSource) {// create an EventSource instance and input the server address var source = new EventSource ('/TestHTML5/ServerSentEvent');} else {console. log ("Your browser doesn't support server-sent event");} // listens for message events and waits for the data source sent from the server. addEventListener ('message', function (event) {// The data attribute in the event parameter is the data console sent by the server. log (event. data) ;}, false); // EventSource also provides onopen and onerror event source. addEventListener ('open', function (event) {}, false); source. addEventListener ('error', function (event) {if (event. readyState = EventSource. CLOSED) {}}, false );

 

On the server side, use the response object to write data to the client in the Servlet doGet method implemented in Java.

List 10. Simple server implementation
// Content-Type must be set to text/event-stream response. setHeader ("Content-Type", "text/event-stream"); response. setHeader ("Cache-Control", "no-cache"); response. setCharacterEncoding ("UTF-8"); String id = new Date (). toString (); response. getWriter (). println ("id:" + id); // write two lines of data to the client. getWriter (). println ("data: server-sent event is working. "); response. getWriter (). println ("data: test server-sent event multi-line data"); response. getWriter (). println (); response. getWriter (). flush ();

 

Figure 6. Server-Sent Events running result

Why is it better than cookie?

1. Calmly speaking, WebStorage generally provides 5 MB of storage space in browsers, which is insufficient for storing videos and images. However, most operations are sufficient.

2. In terms of security, WebStorage is not a browser sent as an HTTP header, so it is relatively secure.

3. In terms of traffic, because WebStorage is not transferred to the server, unnecessary traffic can be saved, which is good for frequently accessed webpages or mobile devices.

This does not mean that WebStorage can replace cookies. Instead, with WebStorage, the cookie can only do what it should do-as a channel for client-server interaction to maintain the client status. Therefore, WebStorage is better than cookie as a local storage solution.

Notes

1. browser compatibility. This is the easiest way to implement almost all new HTML5 features. Because IE8 + browsers support this feature, IE User Data can be used in IE7 and IE6.

2. Because localStorage and sessionStorage are both objects, you can use ". key" or "[key]" to obtain and modify key-value pairs every year. However, this is not recommended.

localStorage.userName='Frank';console.log(localStorage['userName']);

3. Although localStorage is stored locally, different browsers store data independently. Therefore, localStorage stored on Chrome cannot be obtained on FireFox.

4. localStorage and sessionStorage can only store string types. For complex objects, you can use stringify and parse of JSON objects provided by ECMAScript. For earlier IE versions, you can use json2.js.

5. In addition to the console, Chrome also provides a very intuitive display mode for local storage, which is convenient for debugging.

Conclusion

This article details the application of postMessage (send) and onmessage APIs on the client. We can see that the application modes of these two methods are similar in different scenarios. PostMessage is used to transmit data, while onmessage is used to receive data. Understanding this group of Apis will be helpful for the development of HTML 5 applications in the future. In this article, the Web Workers, Cross-document messaging, and WebSockets Code passed the test in Firefox 14. The Server-Sent Events Code passed the test in Chrome 16.

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.