HTML5 API-cross-document message

Source: Internet
Author: User

 
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 );}}};

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.