window.postMessage is often used by people for cross-domain data transfer. The following will introduce the basic usage tutorial of postMessage API in HTML5. Friends in need can refer to
About postMessage
Although window.postMessage is said to be a function of HTML5, it supports IE8. If your website does not need to support IE6 and IE7, 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 information:
//弹出一个新窗口 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);
To delay, we usually use timing The setTimeout delay is used again.
Accepted page
//监听消息反馈 window.addEventListener('message',function(event) { if(event.origin !== 'http://haorooms.com') return; //这个判断一下是不是我这个域名跳转过来的 console.log('received response: ',event.data); },false);
As shown below, the accepting page gets data
If iframe is used, the code should be written like this :
//捕获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);
Accept data
//响应事件 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);
The above code snippet 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.
Calling the instance
1. Create a Worker instance in the main thread and listen to the onmessage event
<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('compute.js'); //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>
In the client's compute.js, just simply repeat The sum operation is performed once, and finally the result is returned 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.
2. Call the postMessage method in compute.js to return 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; } } // 调用 postMessage 向主线程发送消息 postMessage(sum); } postMessage("Before computing,"+new Date()); timedCount(); postMessage("After computing,"+new Date());
The above is the entire content of this article. I hope it will be helpful to everyone's learning. More related Please pay attention to the PHP Chinese website for content!
Related recommendations:
New eight types of INPUT input for HTML5
How to use HTML5 to operate WebSQL database
The above is the detailed content of Basic use of postMessage API in HTML5. For more information, please follow other related articles on the PHP Chinese website!

The usage methods of HTML tags and attributes include: 1. Basic usage: Use tags such as and, and add necessary information through attributes such as src and href. 2. Advanced usage: Use data-* custom attributes to achieve complex interactions. 3. Avoid common mistakes: Make sure the property values are surrounded by quotes. 4. Performance optimization: Keep it simple, use standard attributes and CSS class names to ensure that the image has alt attributes. Mastering these will improve web development skills.

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
