93

I'm trying to make a trivial postMessage example work...

  • in IE10
  • between windows/tabs (vs. iframes)
  • across origins

Remove any one of these conditions, and things work fine :-)

But as far as I can tell, between-window postMessage only appears to work in IE10 when both windows share an origin. (Well, in fact -- and weirdly -- the behavior is slightly more permissive than that: two different origins that share a host seem to work, too).

Is this a documented bug? Any workarounds or other advice?

(Note: This question touches on the issues, but its answer is about IE8 and IE9 -- not 10)


More details + example...

launcher page demo

<!DOCTYPE html>
<html>
  <script>
    window.addEventListener("message", function(e){
      console.log("Received message: ", e);
    }, false);
  </script>
  <button onclick="window.open('http://jsbin.com/ameguj/1');">
    Open new window
  </button>
</html>

launched page demo

<!DOCTYPE html>
<html>
  <script>
    window.opener.postMessage("Ahoy!", "*");
  </script>
</html>

This works at: http://jsbin.com/ahuzir/1 -- because both pages are hosted at the same origin (jsbin.com). But move the second page anywhere else, and it fails in IE10.

Community
  • 1
  • 1
Bosh
  • 6,684
  • 6
  • 45
  • 68
  • 1
    http://blogs.msdn.com/b/ieinternals/archive/2009/09/16/bugs-in-ie8-support-for-html5-postmessage-sessionstorage-and-localstorage.aspx – EricLaw Nov 20 '13 at 00:47
  • 5
    Please consider changing the accepted answer to one that answers the question rather than one that lists MessageChannel as your best bet when MessageChannel requires postMessage to get it working. I spent over an hour playing with MessageChannel only to find that the one viable solution is an iframe proxy. – Akrikos Oct 07 '14 at 14:39
  • 1
    If your window.open is just a popup dialog, you could avoid it altogether and use an iframe in a js modal. Something like [jQuery Dialog](https://api.jqueryui.com/dialog/) or [Bootstrap Modal](http://getbootstrap.com/javascript/#modals) is how I implemented it. Then you can use `window.parent.postMessage` in IE. – styfle Jul 07 '15 at 00:03
  • @Bosh as my answer seems to work in 2018 and requires no proxy frame, would you mind setting thatone as the accepted answer as it seems to help to us, unfortunate ones who still have to support old ie – Bruno Laurinec Apr 03 '18 at 15:34

8 Answers8

62

I was mistaken when I originally posted this answer: it doesn't actually work in IE10. Apparently people have found this useful for other reasons so I'm leaving it up for posterity. Original answer below:


Worth noting: the link in that answer you linked to states that postMessage isn't cross origin for separate windows in IE8 and IE9 -- however, it was also written in 2009, before IE10 came around. So I wouldn't take that as an indication that it's fixed in IE10.

As for postMessage itself, http://caniuse.com/#feat=x-doc-messaging notably indicates that it's still broken in IE10, which seems to match up with your demo. The caniuse page links to this article, which contains a very relevant quote:

Internet Explorer 8+ partially supports cross-document messaging: it currently works with iframes, but not new windows. Internet Explorer 10, however, will support MessageChannel. Firefox currently supports cross-document messaging, but not MessageChannel.

So your best bet is probably to have a MessageChannel based codepath, and fallback to postMessage if that doesn't exist. It won't get you IE8/IE9 support, but at least it'll work with IE10.

Docs on MessageChannel: http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx

ShZ
  • 6,188
  • 1
  • 23
  • 22
  • 8
    How would you create a `MessageChannel`-based codepath that works? You still need functioning `postMessage` to get the channel's port to the other window. – balpha Oct 22 '13 at 09:51
  • 1
    Using `postMessage` with the new `MessageChannel` API will work across new windows and origins. The working is a little awkward I guess, but basically: `postMessage('foo', '*')` is bad, `postMessage('foo', [messageChannel.port2])` is good. – ShZ Oct 22 '13 at 19:01
  • 3
    I can't for the life of me get postMessage working with a cross-domain popup window using the latest version of IE (11) and the MessageChannel API. And honestly I can't find anywhere else on the InterWebs other than this answer indicating that this specific scenario should work. Can anyone point to an example proving that it works? I'd be forever grateful. – Todd Menier Jan 24 '14 at 23:26
  • 4
    MessageChannel shouldn't work for the same reason postMessage won't. Microsoft needs to fix the cross-process marshalling. http://blogs.msdn.com/b/ieinternals/archive/2009/09/15/bugs-in-ie8-support-for-html5-postmessage-sessionstorage-and-localstorage.aspx – EricLaw Sep 02 '14 at 13:34
  • 9
    This answer is annoying because it gives us false hope. The answer is: it won't work without a proxy because postMessage is _required_ to get MessageChannel working (at least in every demo I've seen). Unless someone shows me a demo of MessageChannel working without postMessage or postMessage('name', '', [messageChannel.port2]) working cross domain (I couldn't get it to work), I won't believe this works without a proxy frame. – Akrikos Oct 02 '14 at 22:21
  • Did you try easyXDM for XDM postMessage in IE/Edge? https://easyxdm.net/ ? – OG Sean Dec 12 '19 at 19:38
  • Check my answer below, it makes the postMessage work for IE10 and 11 without any proxy – Bruno Laurinec Feb 13 '20 at 11:45
30

Create a proxy page on the same host as launcher. Proxy page has an iframe with source set to remote page. Cross-origin postMessage will now work in IE10 like so:

  • Remote page uses window.parent.postMessage to pass data to proxy page. As this uses iframes, it's supported by IE10
  • Proxy page uses window.opener.postMessage to pass data back to launcher page. As this is on same domain - there are no cross-origin issues. It can also directly call global methods on the launcher page if you don't want to use postMessage - eg. window.opener.someMethod(data)

Sample (all URLs are fictitous)

Launcher page at http://example.com/launcher.htm

<!DOCTYPE html>
<html>
    <head>
        <title>Test launcher page</title>
        <link rel="stylesheet" href="/css/style.css" />
    </head>
    <body>

    <script>
        function log(msg) {
            if (!msg) return;

            var logger = document.getElementById('logger');
            logger.value += msg + '\r\n';
        }            

        function toJson(obj) {
            return JSON.stringify(obj, null, 2);
        }

        function openProxy() {
            var url = 'proxy.htm';
            window.open(url, 'wdwProxy', 'location=no');
            log('Open proxy: ' + url);
        }

        window.addEventListener('message', function(e) {
            log('Received message: ' + toJson(e.data));
        }, false);
    </script>
    
    <button onclick="openProxy();">Open remote</button> <br/>
    <textarea cols="150" rows="20" id="logger"></textarea>

    </body>
</html>

Proxy page at http://example.com/proxy.htm

<!DOCTYPE html>
<html>
    <head>
        <title>Proxy page</title>
        <link rel="stylesheet" href="/css/style.css" />
    </head>
    <body>

    <script>
        function toJson(obj) {
            return JSON.stringify(obj, null, 2);
        }

        window.addEventListener('message', function(e) {
            console.log('Received message: ' + toJson(e.data));

            window.opener.postMessage(e.data, '*');
            window.close(self);
        }, false);
    </script>

    <iframe src="http://example.net/remote.htm" frameborder="0" height="300" width="500" marginheight="0" marginwidth="0" scrolling="auto"></iframe>

    </body>
</html>

Remote page at http://example.net/remote.htm

<!DOCTYPE html>
<html>
    <head>
        <title>Remote page</title>
        <link rel="stylesheet" href="/css/style.css" />
    </head>
    <body>

    <script>
        function remoteSubmit() {
            var data = {
                message: document.getElementById('msg').value
            };

            window.parent.postMessage(data, '*');
        }
    </script>
    
    <h2>Remote page</h2>

    <input type="text" id="msg" placeholder="Type a message" /><button onclick="remoteSubmit();">Close</button>

    </body>
</html>
Community
  • 1
  • 1
LyphTEC
  • 1,019
  • 1
  • 11
  • 11
  • Your answer would be better if it included a link to the Microsoft example page & workaround page linked to in other answers. Workaround: http://blogs.msdn.com/b/ieinternals/archive/2009/09/16/bugs-in-ie8-support-for-html5-postmessage-sessionstorage-and-localstorage.aspx Example (from workaround page): http://www.debugtheweb.com/test/xdm/origin/ – Akrikos Oct 02 '14 at 22:26
  • Also, your example page now links to a godaddy page not found. – Akrikos Oct 02 '14 at 22:28
  • 9
    huh? ... all URLs are EXAMPLES and are not meant to actually point to existing pages... from the listed source you can determine what needs to be done to get it working.. – LyphTEC Oct 30 '14 at 01:00
  • Thanks for the clarification. :-) – Akrikos Oct 30 '14 at 13:27
29

== WORKING SOLUTION IN 2020 without iframe ==

Building on answer by tangle, I had success in IE11 [and emulated IE10 mode] using following snippet:

var submitWindow = window.open("/", "processingWindow");
submitWindow.location.href = 'about:blank';
submitWindow.location.href = 'remotePage to comunicate with';

Then I was able to communicate using typical postMessage stack, I'm using one global static messenger in my scenario (alotough I don't suppose it's of any signifficance, I'm also attaching my messenger class)

var messagingProvider = {
    _initialized: false,
    _currentHandler: null,

    _init: function () {
        var self = this;
        this._initialized = true;
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

        eventer(messageEvent, function (e) {
            var callback = self._currentHandler;
            if (callback != null) {
                var key = e.message ? "message" : "data";
                var data = e[key];
                callback(data);
            }
        }, false);
    },

    post: function (target, message) {
        target.postMessage(message, '*');
    },

    setListener: function (callback) {
        if (!this._initialized) {
            this._init();
        }

        this._currentHandler = callback;
    }
}

No matter how hard I tried, I wasn't able to make things work on IE9 and IE8

My config where it's working:
IE version: 11.0.10240.16590, Update versions: 11.0.25 (KB3100773)

Bruno Laurinec
  • 698
  • 2
  • 10
  • 22
  • 6
    I just have to say - in case anyone else is looking at this workaround thinking "no way, that couldn't possibly fix it" - yes, it actually fixed the inability to postMessage to the window.opener in IE11. Unbelievable. – dkr88 Oct 20 '16 at 19:20
  • 1
    No way... I was like 2 days trying and this "solve" the problem – lmiguelmh Jan 27 '17 at 19:48
  • works like charms and mysterious!! (IE10.0.9200, win7) – Simon Apr 02 '18 at 23:44
  • Can you provide a full Example for this workaround ? – msm2020 Jul 01 '20 at 18:47
  • The whole trick is the 3 lines mentioned in the beginning of the solution – Bruno Laurinec Jul 06 '20 at 10:51
  • @BrunoLaurinec Is the `submitWindow.location.href = 'about:blank';` line required before it is reassigned to the actual remotePage? – Sid Jonnala Aug 21 '20 at 17:17
  • 1
    @SidJonnala not really, but I would recommend that. If you reassign to actual remote page immediately and your page takes 3-4s to load [might happen from time to time] then you risk that your window.open('/') page loads and confuses the user – Bruno Laurinec Aug 25 '20 at 13:40
2

Building upon the answers by LyphTEC and Akrikos, another work-around is to create an <iframe> within a blank popup window, which avoids the need for a separate proxy page, since the blank popup has the same origin as its opener.

Launcher page at http://example.com/launcher.htm

<html>
  <head>
    <title>postMessage launcher</title>
    <script>
      function openWnd() {
        var w = window.open("", "theWnd", "resizeable,status,width=400,height=300"),
            i = w.document.createElement("iframe");

        i.src = "http://example.net/remote.htm";
        w.document.body.appendChild(i);

        w.addEventListener("message", function (e) {
          console.log("message from " + e.origin + ": " + e.data);

          // Send a message back to the source
          e.source.postMessage("reply", e.origin);
        });
      }
    </script>
  </head>
  <body>
    <h2>postMessage launcher</h2>
    <p><a href="javascript:openWnd();">click me</a></p>
  </body>
</html>

Remote page at http://example.net/remote.htm

<html>
  <head>
    <title>postMessage remote</title>
    <script>
      window.addEventListener("message", function (e) {
        alert("message from " + e.origin + ": " + e.data);
      });

      // Send a message to the parent window every 5 seconds
      setInterval(function () {
        window.parent.postMessage("hello", "*");
      }, 5000);
    </script>
  </head>
  <body>
    <h2>postMessage remote</h2>
  </body>
</html>

I'm not sure how fragile this is, but it is working in IE 11 and Firefox 40.0.3.

tangle
  • 83
  • 1
  • 6
  • 1
    ... and now it doesn't work (silent failure in popup window to ` – tangle Sep 14 '15 at 05:13
1

Right now, (2014-09-02), Your best bet is to use a proxy frame as noted in the msdn blog post that details a workaround for this issue: https://blogs.msdn.microsoft.com/ieinternals/2009/09/15/html5-implementation-issues-in-ie8-and-later/

Here's the working example: http://www.debugtheweb.com/test/xdm/origin/

You need to set up a proxy frame on your page that has the same origin as the popup. Send information from the popup to the proxy frame using window.opener.frames[0]. Then use postMessage from the proxy frame to the main page.

James Irwin
  • 1,031
  • 8
  • 18
Akrikos
  • 3,354
  • 2
  • 20
  • 20
1

This solution involves adding the site to Internet Explore's Trusted Sites and not in the Local Intranet sites. I tested this solution in Windows 10/IE 11.0.10240.16384, Windows 10/Microsoft Edge 20.10240.16384.0 and Windows 7 SP1/IE 10.0.9200.17148. The page must not be included in the Intranet Zone.

So open Internet Explorer configuration (Tools > Internet Options > Security > Trusted Sites > Sites), and add the page, here I use * to match all the subdomains. Make sure the page isn't listed in the Local intranet sites (Tools > Internet Options > Security > Local Intranet > Sites > Advanced). Restart your browser and test again.

Add to trusted sites in Internet Explorer

In Windows 10/Microsoft Edge you will find this configuration in Control Panel > Internet Options.

UPDATE

If this doesn't work you could try resetting all your settings in Tools > Internet Options > Advanced Settings > Reset Internet Explorer settings and then Reset: use it with caution! Then you will need to reboot your system. After that add the sites to the Trusted sites.

See in what zone your page is in File > Properties or using right click.

Page properties in internet explorer

UPDATE

I am in a corporate intranet and sometimes it works and sometimes it doesn't (automatic configuration? I even started to blame the corporate proxy). In the end I used this solution https://stackoverflow.com/a/36630058/2692914.

Community
  • 1
  • 1
lmiguelmh
  • 2,259
  • 27
  • 46
0

This Q is old but this is what easyXDM is for, maybe check it out as a potential fallback when you detect a browser that does not support html5 .postMessage :

https://easyxdm.net/

It uses VBObject wrapper and all types of stuff you'd never want to have to deal with to send cross domain messages between windows or frames where window.postMessage fails for various IE versions (and edge maybe, still not sure 100% on the support Edge has but it seems to also need a workaround for .postMessage)

OG Sean
  • 760
  • 6
  • 17
-3

MessageChannel doesn't work for IE 9-11 between windows/tabs since it relies on postMessage, which is still broken in this scenario. The "best" workaround is to call a function through window.opener (ie. window.opener.somefunction("somedata") ).

Workaround in more detail here

user1337489
  • 115
  • 1
  • 4