Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE8/9 window.postMessage not working, but why?

The "postMessage" is an HTML5 API, it is available in all major browsers including IE8/9. What I am trying to do is to create a popup window from a page, and be able to talk to the popup window using "postMessage". This works in every browser except IE8/9. Disappointed!

It looks like IE8/9 only allows the communication between iframes, but not between two windows, even the windows are within the same hierarchy.

like image 410
Rn2dy Avatar asked Dec 11 '12 23:12

Rn2dy


People also ask

What is window opener postMessage?

postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

Can I use window postMessage?

window. postMessage() is a safe way to send messages between windows in different domains or origins. One can also post to an IFrame. The data being sent is serialized using the structured clone algorithm and will accept almost any type of simple or complex data.

Is postMessage asynchronous?

The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it.

Is window postMessage secure?

Security-Reviewing Uses of postMessage()postMessage is generally considered very secure as long as the programmer is careful to check the origin and source of an arriving message. Acting on a message without verifying its source opens a vector for cross-site scripting attacks.


2 Answers

I found that .postMessage() in IE9 was unreliable unless I used Strings.

My workaround was to simply call .postMessage(JSON.stringify({object: 'data'})) and use JSON.parse() in the onMessage() function on the other end.

like image 143
simon Avatar answered Sep 19 '22 01:09

simon


The .postMessage method works, you just need to understand how it works from IE8 and up. Unfortunately, for IE8 and IE9 it will not do what you're seeking (though it does in IE10). While you can send messages between frames in IE8/9, you cannot send messages to a separate window.

There is a work-around that works in some instances. Martin Beeby discusses it in the last paragraph of his blog post on the issue: PostMessage Popups and IE.

For more on this, and a few other caveats, see Eric Lawrence's post on MSDN.

like image 32
Sampson Avatar answered Sep 18 '22 01:09

Sampson