How to use the postMessage manual in HTML5
This article mainly introduces the relevant knowledge of "how to use postMessage manual in HTML5". Xiaobian shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to use postMessage manual in HTML5" can help you solve the problem.
When coding code, we often encounter the following cross-domain situations:
1, nested iframes within the page, messaging with iframes
2. Message transfer between pages and multiple pages
In response to these headache cross-domain problems, html5 specially introduced a new feature-postMessage (cross-document message transmission). PostMessage requires two parameters, data and originUrl. Data refers to the content that needs to be passed, but some browsers can only handle string parameters, so we generally serialize the data, that is, JSON.stringify(), originUrl refers to the target url, the specified window.
The following examples are directly thrown, I believe it is easier for everyone to understand and write.
1, nested iframes within the page
Parent Page:
html:
hello word postMessage
js:
_window.onload=function(){ window.frames[0].postMessage('postMessage','http://127.0.0.1:8082/index2.html')} window.addEventListener('message',function(e){ console.log(e) document.getElementById('parent').style.color=e.data})
Subpages:
html:
receive information
js:
window.addEventListener('message',function(e){ console.log(e) let color = document.getElementById('button').style.color window.parent.postMessage(color,'http://127.0.0.1:8081/index.html')});function changeColor(){ let buttonColor = document.getElementById('button').style.color buttonColor='#f00' window.parent.postMessage(buttonColor,'http://127.0.0.1:8081/index.html')}
The parent page passes messages to the iframe via the postMessage method, while the child page listens for messages via the window.addEventListener method to get the values passed to the parent page. As shown below, data is the value passed by the parent page.
The child page passes messages to the parent page, also through the postMessage method to pass messages, not through the window.parent.postMessage(data,url) way to pass values. The parent page gets the same value as listening for message events.
2. Transfer messages between multiple pages
Parent Page:
html: