Window.postmessage Resolving cross-domain

Source: Internet
Author: User

First, the basic principle

HTML5 introduced the cross-document communication API (Cross-document messaging) in order to resolve cross-domain. This API adds a new Window.postmessage method to the Window object, allowing cross-window communication regardless of whether the two windows are of the same origin. This feature is supported by Internet Explorer 8+, Chrome,firefox, opera, and Safari.

Second, the test steps

1. Create a.html

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Window.postmessage Resolving cross-domain a.html</title></Head><Body><Script>window.onload= function() {        varSubwin=window.open ('http://localhost:8081/b.html', 'title'); //The parent window http://localhost:8080/a.html the http://localhost:8081/b.html message to the child window, calling the PostMessage method. Subwin.postmessage ('I'm going to send you a message!', 'http://localhost:8081'); } window.addeventlistener ('message', function(e) {Console.log ('a.html received message:', E.data); });</Script></Body></HTML>

Sends a message and listens for messages.

2. Create b.html

<Script>  varMessagefunc= function(event) {if(Event.source!=window.parent) {return; }      varData=Event.data,//messageOrigin=Event.origin,//Message Source AddressSource=Event.source;//Source Window Object      if(Origin== "http://localhost:8080") {Console.log ('b.html received message:', data); } source.postmessage ('I've already received the message!', origin);      }; if (typeofWindow.addeventlistener!= 'undefined') {Window.addeventlistener ('message', Messagefunc,false); } Else if (typeofwindow.attachevent!= 'undefined') {window.attachevent ('message', Messagefunc); }</Script>

3. Open two HTTP servers

4. Open the browser to see the result: http://localhost:8080/a.html

Window.postmessage Resolving cross-domain

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.