HTML5: Use postMessage to implement Ajax cross-origin requests. html5postmessage

Source: Internet
Author: User

HTML5: Use postMessage to implement Ajax cross-origin requests. html5postmessage

 

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: <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.