HTML5 of cross-domain solutions PostMessage

Source: Internet
Author: User

Problem Scenario:

Web is a static page embedded in the mobile client, in order to statistical user behavior need to introduce GA, but GA must be at www, even if it is localhost, this is the contradiction. The solution is to use Iframe,iframe in the page under another domain name, and then call the GA method in the IFRAME. It is clear that cross-domain communication of the IFRAME must be resolved.

var frame=document.getelementbyid ("Gaframe");    Document.body.onclick=function() {        var senddata={            "name": "Deals _list ",            " event ":" Deals_click ",            " E_data ":" This is the data sent "        }        Frame.contentWindow.postMessage (SendData,"*")    }

Sends a message to the IFRAME each time the specified area is clicked, then listens for the message data in the IFRAME and sends the GA.

varOnMessage =function(e) {varData=E.data; GA (' Send ', ' pageview ', '/' +data); }     functioninit () {if(Window.addeventlistener) {//All browsers except IE before version 9Window.addeventlistener ("message", OnMessage,false); } Else {             if(window.attachevent) {//IE before version 9Window.attachevent ("OnMessage", OnMessage);     }         }     }; Init ();

Well, the actual scene and methods are finished, start learning relevant knowledge.

Window.postmessage

window.postMessageis a method for secure use of cross-origin communication. Typically, scripts on different pages are allowed to access each other only in this case, and only when the page where they are executed uses the same protocol (usually HTTP), the same port (HTTP defaults to 80 ports), and the same host (two pages of Document.domain Values are the same). In the case of proper use, window.postMessage a controlled mechanism is provided to safely circumvent this limitation.

window.postMessage, when called, the pending script must be completed before the messageevent is dispatched to the target window (for example: If an event handler calls Window.postmessage, the remaining event handlers hang timeouts, and so on). Messageevent has a message type, which is set to the first parameter value provided to window.postMessage的data属性, When the corresponding window calls Window.postmessage, the Origin property of the source of the Window.postmessage main document is called the source attribute, which refers to the window that called Window.postmessage. (The other standard properties of the event are present with the corresponding expected values.)

Grammar:

Otherwindow.postmessage (message, targetorigin);
Otherwindow
Referencing another window, such as an IFRAME in the above instance, contentWindow is the Window object in the IFRAME.
Message
Data that is sent to other windows

Targetorigin
Target source, you can restrict the receipt of data from only one URL

Listening to send events
false ); function ReceiveMessage (event) {  if (event.origin!== "http://example.org:8080")      return;   //  ...}

Data: from other windows.

Origin: The window URL that calls PostMessage.

Source: A reference to the Send Message window. You can use this method to make a two-way communication between windows from different sources.

Security

varPopup =window.open (... popup details ...);//When the popup had fully loaded, if not blocked by a popup blocker://This does nothing, assuming the window hasn ' t changed it location.Popup.postmessage ("The user is ' Bob ' and the password are ' secret '",                  "Https://secure.example.net");//This would successfully queue a message to being sent to the popup, assuming//The window hasn ' t changed its location.Popup.postmessage ("Hello there!", "http://example.org");functionReceiveMessage (event) {//Do We trust the sender of this message? (Might be  //different from what we originally opened, for example).  if(Event.origin!== "http://example.org")    return; //Event.source is popup  //Event.data is "Hi there yourself! The secret response is:rheeeeet! "}window.addeventlistener ("Message", ReceiveMessage,false);

/** In the popup ' s scripts, running on *///called sometime after PostMessage is calledfunctionReceiveMessage (event) {//Do We trust the sender of this message?  if(Event.origin!== "http://example.com:8080")    return; //Event.source is Window.opener  //event.data is "Hello there!"  //assuming you ' ve verified the origin of the received message (which  //a convenient idiom for replying to a must  //message is to call PostMessage on Event.source and provide  //Event.origin as the targetorigin.Event.source.postMessage ("Hi there yourself! The secret response "+" is:rheeeeet! ", Event.origin);} Window.addeventlistener ("Message", ReceiveMessage,false);

The web worker is used in PostMessage and OnMessage

Create Worker instances in the main thread and listen for onmessage events
functioninit () {varWorker =NewWorker (' Compute.js '); //The event parameter has the Data property, which is the results returned in the child threadWorker.onmessage=function(event) {//Add the result of the thread returned to the DIVdocument.getElementById ("Result"). InnerHTML + =Event.data+ "<br/>";      }; }  </script> 

In the client's compute.js, it simply repeats multiple addition and operation, and finally returns the result to the main thread through the PostMessage method, which is to wait for a period of time. During this time, the main thread should not be blocked, the user can drag and drop the browser, zoom out browser window and other operations testing this phenomenon. The result of this non-blocking main thread is what the Web Workers wants to achieve.

Call the PostMessage method in Compute.js to return the result of the calculation
var i=0;   function Timedcount () {      for (var j=0,sum=0;j<100;j++) {           for ( var i=0;i<100000000;i++) {              sum+ =i;          }      }       // call PostMessage to send a message to the main thread      postMessage (sum);  }  PostMessage ("before computing," +new  Date ());  Timedcount ();  PostMessage ("after computing," +new Date ());

HTML5 of cross-domain solutions PostMessage

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.