Is there a standard way to recognize your own postMessage in an onmessage event handler?

I have an iframe based widget that uses postMessage to communicate with a parent. This means that I am sending a message from an iframe to request the size itself. The json data is also currently interfering with messages sent by other widgets / scripts on the parent page.

So, I need a way to distinguish my own posts from others.

Now I just want to add the parameter { app: 'Poules.com', [...] } and check this parameter before processing the message.

But before I do this: are there any contracts for this already?

Sending Code:

 parent.postMessage( JSON.stringify(data), page.widgetOrigin ); 

Final result:

 poules.sdk.receiveMessage = function(event) { var data = JSON.parse( event.data ); switch ( data.message ) { case 'requestResize': poules.sdk.requestResize( data ); break; case 'loginSuccess': poules.sdk.triggerLoginEvent( data ); break; default: throw "poules.sdk: can't parse message: " + event.data; }; } 
+5
source share
1 answer

When you receive a message event, you should check event.origin to make sure it comes from the source from which you want to receive messages. This is usually enough to distinguish them from other posts.

So:

 poules.sdk.receiveMessage = function(event) { if (event.origin != "http://poules.com") { // or whatever return; } var data = JSON.parse( event.data ); switch ( data.message ) { case 'requestResize': poules.sdk.requestResize( data ); break; case 'loginSuccess': poules.sdk.triggerLoginEvent( data ); break; default: throw "poules.sdk: can't parse message: " + event.data; }; } 

There are two reasons for this:

  • Filters messages from windows that are not related to what you are doing, and

  • It filters out malicious messages, trying to personalize your widget and trick the main page, doing what should not be done

Read more about event.origin in MDN ; here's a note on how the string is formed:

Start

The start of the window that sent the message at the time postMessage called up. This line represents the concatenation of the protocol and ": //", the host name, if one exists, and ":", followed by the port number, if the port is present, and differs from the default port for this protocol. Examples of typical origin are https://example.org (meaning port 443), http://example.net (meaning port 80) and http://example.com:8080 . Note that this origin is not guaranteed as the current or future origin of this window, which may have been moved to another location since postMessage was called.

+4
source

Source: https://habr.com/ru/post/1209054/


All Articles