Use the postMessage knowledge point in HTML5 to solve the POST cross-origin problem in Ajax, html5postmessage

Source: Internet
Author: User

Use the postMessage knowledge point in HTML5 to solve the POST cross-origin problem in Ajax, 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.

PostMessage is a new API introduced by html5. it allows multiple iframe/window cross-origin communications to solve js cross-origin problems.

HTML5 provides the ability to receive and send information between webpage documents. To use this function, you only need to obtain the instance of the window object in which the webpage is located, and not only web pages with the same origin (domain + port number) can communicate with each other, or even cross-domain communication can be implemented.

Browser support: IE8 +, firefox4 +, chrome8 + opera10 +

1. First, to receive messages sent from other windows, you must listen to the message event of the window object, as shown in the following code:

Copy codeThe Code is as follows:
Window. addEventListener ("message", function () {}, false );

2. Second, use the postMessage method of the window object to send messages to other windows. The method is defined as follows:

Copy codeThe Code is as follows:
OtherWindow. postMessage (message, targetOrigin );

This method uses two parameters. The first parameter is the message text sent, but it can also be any javascript Object. The second parameter is the url address of the window of the object receiving the message (for example: http: 127.0.0.1: 8080/), but we can also use the wildcard "*" in the url string to specify all domains. However, we recommend that you use a specific domain name, otherWindow is a reference to the window object to be sent.

Demo:

Assume that I am binding two domain names under the hosts file:

127.0.0.1 abc.example.com
127.0.0.1 longen.example.com

The pipeline code is as follows:

<Form> <p> <label for = "message" style = "color: red; font-size: 24px;"> send a message to the iframe subwindow: </label> <input type = "text" name = "message" value = "send" id = "message"/> <input type = "submit" value = "submit" id = "submit"/> </p> </form> 

The JS Code is as follows:

Var win = document. getElementById ("iframe "). contentWindow; document. getElementById ("submit "). onclick = function (e) {e. preventDefault (); win. postMessage (document. getElementById ("message "). value, "http://longen.example.com");} window. addEventListener ("message", function (e) {e. preventDefault (); document. getElementById ("test "). innerHTML = "from" + e. origin + "The message passed here: \ n" + e. data;}, false );

The Def.html code is as follows:

HTML code:

<Form> <p> <label for = "message"> send a message to the parent window abc.html: </label> <input type = "text" name = "message" value = "send" id = "message"/> <input type = "submit"/> </p> </form> <p id = "test2"> no information is available. </P>

The JS Code is as follows:

Var parentwin = window. parent; window. addEventListener ("message", function (e) {document. getElementById ("test2 "). innerHTML = "fields from the parent window" + e. origin + ", and content data:" + e. data; parentwin. postMessage ('Hi! You sent me "<span> '+ e. data +'" </span>. ', "Http://abc.example.com") ;}, false );

After clicking the "abc.html" Page, I can see the effect and return the content from def.html. As follows:

We need to know the following information:

You can listen to the message event of the window object to receive messages.
You can obtain the message sending source by accessing the origin attribute of the message event.
You can obtain the message content by accessing the data attribute of the message event.
Use the postMessage method to send messages.
By accessing the source attribute of the message event, you can obtain the window object of the message sending source (accurately, it should be the window proxy object ).
With the basic knowledge above, we can extend to cross-domain Implementation of ajax POST.

Ii. Use the postMessage knowledge point to solve the POST cross-origin problem in ajax.

Principle: When an ajax request (cross-origin domain name is longen.example.com) is sent to a webpage, we should first create a webpage under longen.example.com. now we can embed a hidden domain iframe src path on the abc.html page to point to the def and html pages in the longen.example.com domain. The process is still a cross-document. Now, you can write an ajax request in the window. onmessage event on the def.html page, as shown in the following code:

The abc.html page under abc.example.comis as follows:

The html code is the same as the above. below is the JS Code:

var win = document.getElementById("iframe").contentWindow;document.getElementById("submit").onclick = function(e){   e.preventDefault();   win.postMessage(document.getElementById("message").value,"http://longen.example.com/"); } window.addEventListener("message",function(e){  e.preventDefault();  alert(typeof e.data)  var json = JSON.parse(e.data);   console.log(json);  alert(json.url)},false);

The def.html code is as follows:

The JS Code is as follows:

// Obtain the cross-Origin data window. onmessage = function (e) {$. ajax ({url: 'http: // longen.example.com/webSocket/test.php', type: 'post', dataType: 'text', // data: {msg: e. data}, success: function (res) {var parentwin = window. parent; parentwin. postMessage (res, "http://abc.example.com"); // send data across domains }});};

The test. php code is as follows:

<?php   $data=array(    url =>1,   name =>'2',   'xx-xx'=>"xx" ); echo json_encode($data);?>

The above implementation method can implement cross-origin ajax post.

The above content is about using the postMessage knowledge point in HTML5 to solve the POST cross-origin problem in Ajax. I hope you will like it.

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.