HTML5: Use postmessage to implement Ajax cross-origin requests

Source: Internet
Author: User

Due to restrictions of the same-origin policy, JavaScript has cross-origin communication problems. Typical Cross-origin problems include IFRAME and parent-level communication.

There are several common solutions:
(1) document. Domain + IFRAME; (2) dynamically create scripts; (3) IFRAME + location. Hash; (4) Flash.

We will not elaborate on these methods here, but record the HTML5 window. postmessage. Postmessage compatibilityIE8 +, Firefox, opera, Safari, chrome.

Two Exotic servers are required for testing. Of course, local and online servers can also be used as two exotic servers.If you use phonegap for development, you can install the request file on the client, and then dynamically request the server for data processing to obtain and display the data. In this way, you can use any web development language and method to develop the background required by the phonegap app.

1. postmessage usage

Postmessage is a new API introduced by html5. it allows multiple IFRAME/window cross-origin communications to solve JS cross-origin problems.

Assume that the structure is as follows:

Test.html
<Section id = "wrapper">
<Header>
<H1> postmessage (cross-origin) </Header>
<Article>
<Form>
<P>
<Label for = "message"> send a message to IFRAME: </label>
<Input type = "text" name = "message" value = "son" id = "message"/>
<Input type = "Submit"/>
</P>
</Form>
<H4> Target IFRAME information: </H4>
<P id = "test"> no information </P>
<IFRAME id = "iframe"
Src = "http://xiebiji.com/works/postmessage/iframe.html"> </iframe>
</Article>
</Section>

  

Iframe.html
<Strong> IFRAME points to xiebiji.com </strong>
<Form>
<P>
<Label for = "message"> send a message to the parent window: </label>
<Input type = "text" name = "message" value = "dad" id = "message"/>
<Input type = "Submit"/>
</P>
</Form>
<P id = "test"> no information is available. </P>
Below is the JavaScript code in test.html (send data ):

VaR win = Document. getelementbyid ("iframe"). contentWindow;
Document. queryselector ('form'). onsubmit = function (e ){
Win. postmessage (document. getelementbyid ("message"). value ,"*");
If (E. preventdefault)
E. preventdefault ();
E. returnvalue = false;
}

The key code is as follows:

win.postMessage(document.getElementById("message").value,"*");

Postmessage is a method of communication objects. Therefore, to communicate with IFRAME, the IFRAME object calls the postmessage method. Postmessage has two parameters. The first parameter is the data to be transmitted, and the second parameter is the domain that allows communication. "*" indicates that the accessed domain is not judged and can be understood as allowing communication between all domains.

Then the code in iframe.html that listens to receive data:

VaR parentwin = Window. parent;
Window. onmessage = function (e ){
Document. getelementbyid ("test"). innerhtml = E. Origin + "say:" + E. Data;
Parentwin. postmessage ('Hi! You sent me "<span> '+ E. Data +'" </span>. ',"*");
};

Easy to understand. E. Data contains the transmitted data. E. Origin indicates the source domain.

Then iframe.htmlalso sends the response data to test.html, and test.html receives the data. If the code is the same, no code will be pasted.

Click here to view the demo (code from Joe su)

2. Ajax cross-origin request

. In this way, cross-origin Ajax requests are implemented. It is actually very simple.

Paste the sample code, but it has nothing to do with the above Code.

(Function (){
// Obtain cross-Origin data
Window. onmessage = function (e ){
VaR url = "http://yangzebo.com/demo/noforget/test.php? MSG = "+ E. Data;
// Ajax
VaR xhr = getxhr ();
If (xhr ){
Xhr. Open ("get", URL, true );
Xhr. onreadystatechange = changehandle;
Xhr. Send (null );
} Else {
Alert ("ajax not supported ");
}
Function changehandle () {// return Processing
If (xhr. readystate = 4 ){
VaR parentwin = Window. parent;
Parentwin. postmessage (xhr. responsetext, "*"); // send data across domains
}
}
Function getxhr () {// get XMLHttpRequest
VaR xhr_temp;
If (window. XMLHttpRequest ){
Xhr_temp = new XMLHttpRequest ();
} Else if (window. activexobject ){
Xhr_temp = new activexobject ("Microsoft. XMLHTTP ");
} Else {
Xhr_temp = NULL;
}
Return xhr_temp;
}
};
})();

Then give a demo that is not easy to understand.

If you are interested in code requests, you can use the developer tools. "Zebo male" is read from the database, "My databases.

3. Prompt

Postmessage can be called only when the contentWindow of IFRAME is obtained.

Postmessage must be called after the IFRAME is loaded. (It took me a long time)

Finally, I would like to thank Joe for his prompt and the little sister Hulin who stole the server for testing. : D

[Original post]: http://yangzebo.com/blog? P = 208

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.