HTML5 PostMessage and OnMessage API detailed application

Source: Internet
Author: User

Original address: http://www.ibm.com/developerworks/cn/web/1301_jiangjj_html5message/

Introduction to Web Workersweb Workers

By 2008, when the first draft HTML5 was developed, HTML5 was carrying more and more new features and functions. It not only enhances the performance of Web systems or Web pages, but also adds support for Web application features such as local databases. One of the most important is the support for multithreading. The concept of a worker thread (Web Workers) is presented in HTML5, and three main features of the Web Workers are regulated: long-running (response), ideal startup performance, and ideal memory consumption. Web Workers allows developers to write background programs that can run for long periods of time without being interrupted by the user, to execute transactions or logic, and to ensure that the page responds to the user in a timely manner.

Web Workers provides a way for scripts on web front-end Web pages to run in a background process. Once it is created, Web Workers can send a task request to the task pool through PostMessage, and then return the message to the creator-specified event handler (captured through OnMessage) by PostMessage. The web Workers process handles tasks without affecting the user interface, and it can also use XMLHttpRequest to handle I/O, but in general, background processes, including Web Workers processes, cannot manipulate the DOM. If you want the results of the daemon to be able to change the DOM, you can only process it by returning the message to the creator's callback function.

Browser to HTML5 support situation can refer to the site when the can I use ...

Using PostMessage and OnMessage in Web Workers

First, you need to new a Worker instance in the JavaScript code of the client page, which is the name of the JavaScript file that needs to run in another thread. The OnMessage event is then monitored on this instance. Finally, JavaScript in another thread can pass data between these two threads by calling the PostMessage method.

Listing 1. Create Worker instances in the main thread and listen for onmessage events
OnMessage= function (event) {  //The result of the thread return is added to the div document.getElementById ("result"). InnerHTML + =     event.data+ "<br/>";  };  }  </script>  

In the client's compute.js, it simply repeats multiple addition and operation, and finally returns the result to the main thread through the PostMessage method, which is to wait for a period of time. During this time, the main thread should not be blocked, the user can drag and drop the browser, zoom out browser window and other operations testing this phenomenon. The result of this non-blocking main thread is what the Web Workers wants to achieve.

Listing 2. Call the PostMessage method in Compute.js to return the result of the calculation
var i=0;  function Timedcount () {for  (Var j=0,sum=0;j<100;j++) {for  (var i=0;i<100000000;i++) {  sum+=i;  }  }  postMessage(sum);  }  PostMessage ("Before computing," +new Date ());  Timedcount ();  PostMessage ("After computing," +new Date ());
Figure 1. Running results in the browser

Cross-document Messagingcross-document Messaging Introduction

JavaScript cross-domain issues have been a tricky issue due to the limitations of the same-origin policy. HTML5 provides the ability to receive and send information between Web documents. With this feature, you can communicate with each other and even cross-domain communication between Web pages that have the same origin (domain + port number), as long as you get to the instance of the Window object where the page is located. To receive information sent from other windows, you must listen for the OnMessage event of the Window object, and other windows can pass the data through the PostMessage method. The method uses two parameters: the first parameter is the message text that is sent, but it can be any JavaScript object (through JSON to convert the object to text), the second parameter is the URL address of the object window that receives the message, and you can use the wildcard ' * ' in the URL address string to specify all.

Using PostMessage and onmessage in cross-document messaging

In order to achieve communication between different domains, it is necessary to add two domain names to the hosts file of the operating system for simulation.

Listing 3. Two different domain names are added to the Hosts file
127.0.0.1  parent.com  127.0.0.1  child.com

Embeds a child page through an IFRAME in the parent Web page and calls the PostMessage method in the JavaScript code to send the data to the child window.

Listing 4. A child page is embedded in the parent page and the PostMessage method is called to send the data
 PostMessage(  document.getElementById ("message"). Value, "http://child.com:8080");  }  </script>  

Listen for the OnMessage event in the child window and display the data sent by the parent window with JAVASCRIPT implementation.

Listing 5. Listen for the OnMessage event in the child window, showing the data sent by the parent window
message", function (event) {  //) The data sent by the parent window is displayed in the child window   . document.getElementById ("Content"). innerhtml+=event.data+ "<br/>";  }, False);  </script>  
Figure 2. Parent Window Embedding child window

Figure 3. Parent window sends data to child window

Websocketswebsockets Introduction

In a WEB application, the HTTP protocol determines that the client and server connections are short connections, that is, the client Request, the server Response, and the connection is disconnected. To implement real-time communication between the client and the server, it can only be done through client polling. Server push data is not the literal meaning of the direct push, in fact, the client to take. WebSockets is a new feature introduced by HTML5 specification, used to solve the problem of two-way communication between browser and background server, using WebSockets technology, the backstage can push the message to the front end at any time to ensure the unity of front and rear state.

Using send and OnMessage in WebSockets

Because the text mainly introduces the application of the PostMessage (send) and OnMessage client APIs, and WebSockets involves the implementation of server-side code, this article chooses the simplest server-side framework to write server code. The WebSockets server-side has a Java-based implementation provided by Jetty, Websocket-node based on node. JS, and WebSockets support is also provided directly in. Net 4.5. This article will use the sample code provided by Websocket-node, slightly modified as the server side of the WebSockets. For the introduction and use of node. js, please refer to node. JS official website, node. js, for Websocket-node use refer to Websocket-node.

First, a WebSocket instance is required on the client through JavaScript code new, and the parameter is the implementation of the WebSocket server-side URL address. Then, on this instance, listen to the data sent by the OnMessage event receiving server side. Of course, the client can also call the Send method and send the data to the server side.

Listing 6. Create a WebSocket object and listen for OnMessage events
Connect:function () {     var location = "Ws://localhost:8000/";  Create the WebSockets and pass in the WebSockets server address    this._ws =new WebSocket (location);     This._ws. onmessage=this._onmessage;    The WebSockets also provides OnOpen and OnClose events    This._ws.onopen =this._onopen;     This._ws.onclose =this._onclose;  }

In the _onmessage method, the data is received and displayed on the page

Listing 7. _onmessage method
The _onmessage:function (event) {  //event parameter has the Data property, that is,     if (event.data) {          var messageBox = document, sent over by the server. getElementById (' MessageBox ');          var spantext = document.createelement (' span ');          Spantext.classname = ' text ';  The data sent over the server is displayed in the window         spantext.innerhtml = event.data;          var lineBreak = document.createelement (' br ');          Messagebox.appendchild (spantext);          Messagebox.appendchild (lineBreak);          Messagebox.scrolltop = Messagebox.scrollheight                  -messagebox.clientheight;      }  },

In the _onopen method, the _send method is called to send a message to the server side, which tells the connection has been established. In the _onclose method, set the instance of WebSocket to null to release the resource.

Listing 8. _onopen,_onclose and Send Methods
_onopen:function () {      server._send ("Client:open WebSockets," +new Date ());  },  //message The parameter is the data _send:function (message) {      if (THIS._WS) This._ws that the client sends to the server side          .  Send(message);  },  //This method provides external code call Send:function (text) {      if (text!=null&& text.length >0) C9/>server._send (text);  },   _onclose:function (m) {      this._ws =null;  }

Encapsulating these methods in a server object makes it easy to provide external calls. The user simply calls the server's Connect method to establish the connection and then calls the Send method to send the data.

Listing 9. Encapsulating client Implementations
var Server = {  //external main offer connect and send method    connect:function () {...},     _onopen:function () {...},     _se Nd: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 in the JavaScript language. Only the critical Code section is shown here, and the other code is in the Websocket-node example.

Listing 10. WebSockets server-side simple implementation
Listen for client connection request Wsserver.on (' Connect ', function (connection) {     function sendcallback (err) {         if (err) Console.error ("Send () Error:" + err);     }  Listen for client send data request    Connection.on (' message ', function (message) {         if (message.type = = = ' UTF8 ') {// Distinguish whether the data sent by the client is 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 the Connect button

Figure 5. Enter content, click the Send Message button

Server-sent eventsserver-sent Events Introduction

The HTML5 server-sent event model allows you to push real-time data from the server to the browser. This article describes the use of Eventsource object processing to receive and send data between pages. On the client side, we use Html5+javascript and the server uses Java. In the existing Ajax model, the Web page continuously requests the server to transfer the new data, which is the client's responsibility for requesting the data. In the server-side send mode, instead of executing continuous data requests in the client code, the update is pushed by the server-side push. Once you initialize the Server-sent event in the page, the server-side script will continue to send the update. The client-side JavaScript code shows up as soon as the update is received and the new data is written to the page.

Using OnMessage in Server-sent Events

Server-sent events and WebSockets have the same, WebSockets realizes the two-way communication between server and client, while Server-sent events refers to the one-way communication between server and client, and Server-sent Events also requires server-side implementations, and this article uses Java-based Servlet technology to implement the server side. For the format of the server-side write data to the client, you can refer to the specification document of Server-sent events server-sent events. There is no PostMessage method in Server-sent Events because it is a one-way server-to-client communication.

First, in the client through the JavaScript code new a EventSource instance, the parameter is to implement the EventSource server-side URL address. Then, on this instance, listen to the data sent by the OnMessage event receiving server side.

Listing 11. Create a EventSource object and listen for OnMessage events
if (!! Window. EventSource) {  //Create EventSource instance, incoming server address  var source = new EventSource ('/testhtml5/serversentevent ');  } else {   console.log ("Your browser doesn ' t support server-sent event");  }  Listen for the message event, waiting for the receiving server to send over the data source.addeventlistener ('message', function (event) {  //event parameter Is the data sent by the server  Console.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);

Server-side, using response objects to write data to the client in the Java language implementation of the Servlet Doget method

Listing 10. Simple server-side implementation
Here the 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 Response.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 Run Results

Conclusion

This article details the application of the PostMessage (send) and OnMessage APIs in the client, and you can see that the application patterns of the two methods are similar in different scenarios. PostMessage's role is to pass data, and OnMessage's role is to receive data. Mastering this set of APIs will be helpful for developing HTML 5 applications in the future. The code of this article Web Workers,cross-document messaging,websockets is tested under Firefox 14, and the code for Server-sent Events is tested under Chrome 16.

HTML5 PostMessage and OnMessage API detailed application

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.