Html5 postmessage implements js frontend cross-origin access and call Solutions

Source: Internet
Author: User

For cross-origin access, the JSONP method has been used in the previous demo. For details, see pipeline:

We still follow the same settings as above, assuming we have 2 Domain

Domain1: http: // localhost: 8080 contains an application named htmldomain1 and a page named sender.html.

Domain2: http: // localhost: 8180. Some applications are htmldomain2 and some are called receiver.html.

My current requirement is that, assuming that we have a json data in Domain1, we want javascript in Domain2 to be able to operate on this json data (note that this is already cross-origin, because js on Domain2 operates data on Domain1), what should I do?

The solution is to use the postMessage method of html5.

Domain2 code:

First, we create an HTML page on Domain2, which has no content, and a line of text will mark it as Domain 2, below it will be used by js to fill in data obtained from Domain1 in the future.

   
  Receiver.html<Script type = "text/javascript" src = "js/receiveInfo. js"> </script>            

This page is the page receiver.html on the HTML5 cross-domain website domain2, which will process the page sent by sender.html on the javasdomain1.

When the Domain2 page is loaded, it will call the receiveInfoFromAnotherDomain () function. This function first defines an event listening function, which only accepts events from Domain1 (http: // localhost: 8080, otherwise, the information load is separated from the event, that is, json data, and then displayed at the bottom of the page:

// This function is used to process the information sent from the sender on Domain1, and then print them out function receiveInfoFromAnotherDomain () {console. log ("entering method receiveInfoFromAnotherDomain ()"); // first let the window add an event listening function, indicating that it can listen to the message event of the window object // when it is affected by the event, the system first checks whether it is from the specified Domain (not all events lost by the Domain are handled) window. addEventListener ("message", function (ev) {console. log ("the caller callback func has been invoked"); // if it is not from the specified Domain, ignore if (ev. origin! = "Http: // localhost: 8080") {console. log ("the event doesn' t come from Domain1! "); Return;} // now you can process the data. // The console prints the received json data, because we sent the json string to the console. log (ev. data); // convert the json string into a json object, and then extract the original information var personInfoJSON = JSON. parse (ev. data); var name = personInfoJSON. name; var title = personInfoJSON. title; var info = personInfoJSON.info; // construct the information text and display it at the bottom of the page var personInfoString = "from the domain:" + ev. origin + "data from there. "+"
"; PersonInfoString + =" name: "+ name +"
"; PersonInfoString + =" title: "+ title +"
"; PersonInfoString + =" information: "+ info +"
"; Document. body. innerHTML = personInfoString ;});}

Then start Domain2 (http: // localhost: 8180). It will be:

Vc/ix7bU2kRvbWFpbjG1xHNlbmRlci5odG1s0rPD5tbQoaM8L3A + CjxwcmUgY2xhc3M9 "brush: java;"> Sender.html<Script type = "text/javascript" src = "js/sendInfo. js"> </script>

Bytes

<Iframe width = "1200" src = "http: // localhost: 8180/HTML5Domain2/receiver.html"> </iframe>

At the same time, we create a button on the page. When we click it, The json data will be sent to Domain2.

Therefore, js functions are responsible for sending json data in the form of json strings, and then sending information to the Domain2 page in iframe. Note that the receiver's window is in iframe, so we use iframe. postMessage. The first parameter is our information carrier. Here it is a json string, and the second parameter is the target Domain, that is, Domain2.

// Assume that this Domain (Domain1) sends some json information to a page function sendInfoToAnotherDomain () {console in another Domain (Domain2. log ("entering method: sendInfoToAnotherDomain ()"); // first construct an Object that contains the information we want to send to Domain2, and then convert it into a json string var personInfo = new Object; personInfo. name = 'Charles '; personInfo. title = "technical lead"; personInfo.info = "talent man"; var str = JSON. stringify (personInfo); console. log ("The information to be send:" + str ); // We send this json string to Domain2 // because the target page on Domain2 is embedded on the home page as iframe, so we get this iframe and then let it send the information // the content of the information is our json string var iframe = window containing the personal information content. frames [0]; iframe. postMessage (str, 'HTTP: // localhost: 100'); console. log ("json string has been sent to domain2 successfully ");}

In this way, we define the sender (Domain1) and receiver (Domain2). Because the sender is embedded with <iframe>, the page looks like:

When you click "click to send the event to the bottom of Domain2" pipeline, you can find that the information exactly matches with sendInfoToAnotherDomain)

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.