Home > Web Front-end > HTML Tutorial > Detailed graphic and text explanation of postMessage API in H5 Detailed introduction

Detailed graphic and text explanation of postMessage API in H5 Detailed introduction

php中世界最好的语言
Release: 2017-12-02 14:45:05
Original
3779 people have browsed it

Regarding postMessage, although it is a function of html5, it supports IE8+. If your website does not need to support IE6 and IE7, you can use window.postMessage. It can be transferred across domains or within the same domain.

I am just giving a simple application scenario. Of course, this function can be used in many places.

If you have a page and get part of the user information on the page, click to enter another page. The other pages cannot get the user information by default. You can pass part of the user information to the page through window.postMessage. in this page. (Of course, you have to consider security and other aspects.)

Code example

Send message:

JavaScript Code copy content to clipboard

//弹出一个新窗口   
var domain = 'https://haorooms.com';   
var myPopup = window.open(domain    
            + '/windowPostMessageListener.html','myWindow');   
  
//周期性的发送消息   
setTimeout(function(){   
    //var message = '当前时间是 ' + (new Date().getTime());    
        var message = {name:"站点",sex:"男"}; //你在这里也可以传递一些数据,obj等   
    console.log('传递的数据是  ' + message);   
    myPopup.postMessage(message,domain);   
},1000);
Copy after login

To To delay it, we usually use the timer setTimeout to delay it before sending it.

Accepted page

JavaScript Code copies content to the clipboard

//Listen to message feedback

window.addEventListener('message',function(event) {   
    if(event.origin !== 'https://haorooms.com') return; //这个判断一下是不是我这个域名跳转过来的   
    console.log('received response:  ',event.data);   
},false);
Copy after login

As shown below, the accepted page gets data

If you are using iframe, the code should be written like this:

JavaScript Code copies the content to the clipboard

//捕获iframe   
var domain = 'https://haorooms.com';   
var iframe = document.getElementById('myIFrame').contentWindow;   
  
//发送消息   
setTimeout(function(){   
    //var message = '当前时间是 ' + (new Date().getTime());    
        var message = {name:"站点",sex:"男"}; //你在这里也可以传递一些数据,obj等   
    console.log('传递的数据是:  ' + message);   
        //send the message and target URI   
    iframe.postMessage(message,domain);    
},1000);
Copy after login

Accepts data

JavaScript Code copies the content to the clipboard Board

//响应事件   
window.addEventListener('message',function(event) {   
    if(event.origin !== 'https://haorooms.com') return;   
    console.log('message received:  ' + event.data,event);   
    event.source.postMessage('holla back youngin!',event.origin);   
},false);
Copy after login

The code snippet above is to feed back information to the message source and confirm that the message has been received. The following are several important event attributes:

source – message source, message sending window/iframe.
origin – URI of the message source (may include protocol, domain name and port), used to verify the data source.
data – Data sent by the sender to the receiver.

Call the instance
Create a Worker instance in the main thread and listen to the onmessage event

JavaScript Code copies content to the clipboard

<html>    
<head>    
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">    
<title>Test Web worker</title>    
<script type="text/JavaScript">    
 function init(){    
  var worker = new Worker(&#39;compute.js&#39;);    
  //event 参数中有 data 属性,就是子线程中返回的结果数据   
  worker.onmessage= function (event) {    
   // 把子线程返回的结果添加到 p 上   
   document.getElementById("result").innerHTML +=    
      event.data+"<br/>";    
  };    
 }    
</script>    
</head>    
<body onload="init()">    
<p id="result"></p>    
</body>    
</html>
Copy after login


In the client's compute.js, it simply repeats the sum operation multiple times, and finally returns the result to the main thread through the postMessage method. The purpose is to wait for a period of time. During this period, the main thread should not be blocked. Users can test this phenomenon by dragging the browser, enlarging or shrinking the browser window, etc. The result of this non-blocking main thread is what Web Workers want to achieve.

Calling the postMessage method in compute.js returns the calculation result

JavaScript Code copies the content to the clipboard

var i=0;    
function timedCount(){    
 for(var j=0,sum=0;j<100;j++){    
  for(var i=0;i<100000000;i++){    
   sum+=i;    
  }    
 }    
 // 调用 postMessage 向主线程发送消息   
 postMessage(sum);    
}    
  
postMessage("Before computing,"+new Date());    
timedCount();    
postMessage("After computing,"+new Date());
Copy after login


I believe after reading these cases You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

Implementation steps of using JS to operate HTTP Cookies

html Implementation steps of dotted border line

What is the common syntax of AJAX

The above is the detailed content of Detailed graphic and text explanation of postMessage API in H5 Detailed introduction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template