Home Web Front-end H5 Tutorial Sharing the basic usage of postMessage API in HTML5

Sharing the basic usage of postMessage API in HTML5

Mar 15, 2017 pm 04:26 PM

window.postMessage is often used by people for cross-domain data transfer. The following will introduce to you the postMessage APIbasic usage tutorial in HTML5. Friends in need can refer to

About postMessage

window.postMessage Although it is a function of html5, it supports IE8+. If your website does not need to support IE6 and IE7 , then you can use window.postMessage. Regarding window.postMessage, many friends said that it can support cross-domain. Yes, window.postMessage is a direct data transfer between the client and the client. It can be transferred across domains or in the same domain.

Application Scenario

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复制内容到剪贴板
//弹出一个新窗口   
var domain = 'http://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 delay, we usually use the timer setTimeout to delay and then use it.

Accepted pages

JavaScript Code复制内容到剪贴板
//监听消息反馈   
window.addEventListener('message',function(event) {   
    if(event.origin !== 'http://haorooms.com') return; //这个判断一下是不是我这个域名跳转过来的   
    console.log('received response:  ',event.data);   
},false);
Copy after login


## are as follows Picture, accept the page and get the data


Sharing the basic usage of postMessage API in HTML5

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

JavaScript Code复制内容到剪贴板
//捕获iframe   
var domain = 'http://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


##Accept data

JavaScript Code复制内容到剪贴板
//响应事件   
window.addEventListener('message',function(event) {   
    if(event.origin !== 'http://haorooms.com') return;   
    console.log('message received:  ' + event.data,event);   
    event.source.postMessage('holla back youngin!',event.origin);   
},false);
Copy after login


##The above code snippet is to feed back information to the message source to confirm that the message has been received. The following are some of the more important event

properties

:

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.



Calling the instance

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


JavaScript Code复制内容到剪贴板
<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 server through the postMessage method. The purpose of a thread 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.

2. Call the postMessage method in compute.js to return the calculation result

JavaScript Code复制内容到剪贴板
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


The above is the detailed content of Sharing the basic usage of postMessage API in HTML5. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles