Using the knowledge point of PostMessage in HTML5 to solve the cross domain problem of post in AJAX

Time:2020-11-29

Due to the limitation of the same source policy, JavaScript has the problem of cross domain communication. The typical cross domain problem is the communication between iframe and its parent. There are several conventional solutions:

(1) document.domain +Iframe; (2) creating script dynamically; (3) iframe+ location.hash ; (4) flash。

PostMessage is a new API introduced by HTML5 to solve the cross domain problem of JS, which allows multiple iframes / windows to communicate across domains.

HTML5 provides the function of receiving and sending information between web documents. Using this function, as long as the instance of the window object where the web page is located can not only communicate with each other, but also realize cross domain communication.

Browser support: IE8 +, firefox4 +, chrome 8 + Opera 10+

1. First, to receive messages 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, you need to use the PostMessage method of the window object to send messages to other windows. This 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 text of the message sent, but it can also be any JavaScript object. The second parameter is the URL address of the object window receiving the message (for example: http:127.0.0.1 : 8080 /), but we can also use the wildcard “*” in the URL address string, Specify all domains, but we still recommend using a specific domain name. Otherwindow is the reference of the window object to be sent.

Demo demo:

If I bind two domain names in the hosts file, as follows:

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

Now if you are in abc.example.com There is one under the domain abc.html Page, in longen.example.com There are def.html Page, now I hope that the two pages under different domain names can communicate with each other, abc.html The code is as follows:

<form> 
   <p> 
    <label for="message" style=" color:red;font-size : 24px; "> Send a message to iframe sub window: < / label > 
    <input type="text" name="message" value="send" /> 
    <input type="submit" value="submit"/> 
   </p> 
</form> 
< H4 > information from target iframe: < / H4 > from target iframe 
<p>No information</p> 
 <iframe 
  src="http://longen.example.com/webSocket/def.html" style="display:none"></iframe>

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: "message from" + e.origin + ":" n "+ e.data;
},false);

Def.html The code is as follows:

HTML code:

<form> 
   <p> 
    < label for = "message" > to the parent window abc.html Send a message: < / label > 
    <input type="text" name="message" value="send" /> 
    <input type="submit" /> 
   </p> 
 </form> 
 <p>No information available. </p>

JS code is as follows:

var parentwin = window.parent; 
window.addEventListener("message",function(e){
    document.getElementById ("test2"). InnerHTML: "domain" + e.origin + ", and content data:" e.data; 
    parentwin.postMessage < span '> "/ span' >. "," http://abc.example.com "";
},false);

When I click abc.html After the page, you can see the effect as follows, from the def.html Back to the content. As follows:

We need to know the following information:

By listening to the message event of window object, you can receive messages.
By accessing the origin property of the message event, you can get the sending source of the message.
The message content can be obtained by accessing the data property of the message event.
Send the message using the PostMessage method.
By accessing the source property of the message event, you can get the window object of the message sending source (to be exact, it should be the proxy object of the window).
With the above basic knowledge points, we can extend to the implementation of Ajax post cross domain issues.

2: Using PostMessage knowledge points to solve the post cross domain problem in Ajax.

Principle: the principle is also very simple, if our domain name abc.example.com Under the abc.html The page needs to send an Ajax request (cross domain, domain name is longen.example.com )Next, let’s take the form of cross page documents first. As above, we can now longen.example.com Next, create a page called def.html . so we’re still here abc.html Page embedding a hidden domain iframe SRC path longen.example.com Under the domain def, HTML page. The process is still similar to cross document, except that it is now in the def.html Page in window.onmessage You can write an Ajax request in the event, as shown in the following code:

abc.example.com Under the abc.html The page is as follows:

HTML code is the same as above, and the following is 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);

def.html The code is as follows:

JS code is as follows:

//Get cross domain 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 
     }
   });
 };

test.php The code is as follows:


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

The above implementation method can realize Ajax post cross domain.

The above content is about using HTML5 PostMessage knowledge points to solve the post cross domain problem in Ajax. I hope you like it.