Basic tutorial on postMessage API in HTML5, html5postmessage

Source: Internet
Author: User

Basic tutorial on postMessage API in HTML5, html5postmessage

About postMessage

Although window. postMessage is html5, it supports IE8 +. If your website does not need to support IE6 or IE7, you can use window. postMessage. About window. postMessage, many friends said that it can support cross-origin. Good, window. postMessage is a direct data transfer between the client and the client, both cross-origin transmission and same-domain transmission.

Application scenarios

I just give a simple example of an Application Scenario. Of course, this function can be used in many places.

If you have a page where you can get some user information and click to enter another page, the other page does not get the user information by default. You can use window. postMessage uploads some user information to this page. (Of course, you need to consider security and other aspects .)

Code example

Sending information:

Copy the content to the clipboard using JavaScript Code
  1. // A new window is displayed.
  2. Var domain = 'HTTP: // haorooms.com ';
  3. Var myPopup = window. open (domain
  4. + '/WindowPostMessageListener.html', 'mywindow ');
  5. // Periodically send messages
  6. SetTimeout (function (){
  7. // Var message = 'current time is '+ (new Date (). getTime ());
  8. Var message = {name: "Site", sex: "male"}; // You can also transmit some data here, such as obj.
  9. Console. log ('transmitted data is '+ message );
  10. MyPopup. postMessage (message, domain );
  11. },1000 );

To delay, we usually use the timer setTimeout to delay and then use it again.

Accepted page

Copy the content to the clipboard using JavaScript Code
  1. // Listen for message feedback
  2. Window. addEventListener ('message', function (event ){
  3. If (event. origin! = 'HTTP: // haorooms.com ') return; // check whether the domain name is redirected.
  4. Console. log ('stored ed response: ', event. data );
  5. }, False );

For example, accept the page to get data

If iframe is used, the code should be written as follows:

Copy the content to the clipboard using JavaScript Code
  1. // Capture iframe
  2. Var domain = 'HTTP: // haorooms.com ';
  3. Var iframe = document. getElementById ('myiframe'). contentWindow;
  4. // Send a message
  5. SetTimeout (function (){
  6. // Var message = 'current time is '+ (new Date (). getTime ());
  7. Var message = {name: "Site", sex: "male"}; // You can also transmit some data here, such as obj.
  8. Console. log ('the transmitted data is: '+ message );
  9. // Send the message and target URI
  10. Iframe. postMessage (message, domain );
  11. },1000 );

Accept data

Copy the content to the clipboard using JavaScript Code
  1. // Respond to the event
  2. Window. addEventListener ('message', function (event ){
  3. If (event. origin! = 'HTTP: // haorooms.com ') return;
  4. Console. log ('message received ed: '+ event. data, event );
  5. Event. source. postMessage ('holla back youngin! ', Event. origin );
  6. }, False );

The above code snippets provide feedback to the source to confirm that the message has been received. The following are several important event attributes:

Source-message source, message sending window/iframe.
Origin-the origin URI (which may contain protocols, domain names, and ports) to verify the data source.
Data-the data sent by the sender to the receiver.

Call an instance
1. Create a Worker instance in the main thread and listen to onmessage events

Copy the content to the clipboard using JavaScript Code
  1. <Html>
  2. <Head>
  3. <Meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1">
  4. <Title> Test Web worker </title>
  5. <Script type = "text/JavaScript">
  6. Function init (){
  7. Var worker = new Worker ('ute. js ');
  8. // The event parameter has the data attribute, Which is the result data returned by the Child thread.
  9. Worker. onmessage = function (event ){
  10. // Add the result returned by the sub-thread to the div
  11. Document. getElementById ("result"). innerHTML + =
  12. Event. data + "<br/> ";
  13. };
  14. }
  15. </Script>
  16. </Head>
  17. <Body onload = "init ()">
  18. <Div id = "result"> </div>
  19. </Body>
  20. </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.

2. The postMessage method is called in compute. js to return the calculation result.

Copy the content to the clipboard using JavaScript Code
  1. Var I = 0;
  2. Function timedCount (){
  3. For (var j = 0, sum = 0; j <100; j ++ ){
  4. For (var I = 0; I <100000000; I ++ ){
  5. Sum + = I;
  6. }
  7. }
  8. // Call postMessage to send messages to the main thread
  9. PostMessage (sum );
  10. }
  11. PostMessage ("Before computing," + new Date ());
  12. TimedCount ();
  13. PostMessage ("After computing," + new Date ());

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.