Assume that a webpage contains a Frame subpage, which is called a webpage as the primary page and a Frame as a subpage. Generally, a message must be sent to the subpage on the homepage, to control sub-pages, a typical application is to embed an advertisement or map application into the page. An advertisement or map is designed as a sub-Frame, which needs to receive control messages from the parent page, functions such as ad screen conversion or map position jump are completed. Generally, advertisement pages or Map pages are provided by third-party service providers, so they and the home page are usually not under the same domain name. Here we access the variables or DOM nodes in the sub-Frame on the home page, because the browser imposes restrictions on this for security, do not allow frames under the same domain name to access each other or modify the variables or attributes on each other's pages. Otherwise, an exception is thrown. To solve the preceding problem, HTML5 introduces a cross-document message mechanism, which allows multiple pages to share data with each other without exposing DOM nodes in the page, this ensures that the page will not be maliciously attacked by data transmission. The instance Code assumes that page A contains A Frame, which contains another page B, which is under different domain names. Now let's see how page A and page B can implement cross-document communication. The JavaScript code on page A is as follows:
var o = document.getElementsByTagName('iframe')[0]; o.contentWindow.postMessage('Hello world', 'http://b.example.org/');
The JavaScript code on page B is as follows:
Window. onmessage = function (event) {if (event. origin = 'HTTP: // example.com ') {// you can filter unwanted messages. If (event. data = 'Hello World') {event. source. postMessage ('hello', event. origin);} else {console. log (event. data );}}};