htmlunit: Incorrect event.source when using postMessage

I’m trying to run some code in htmlunit 3.5.0 that has some iframes and uses code like this:

        var win = window.parent.document.getElementById("op_iframe").contentWindow;
        win.postMessage(mes, "*");

The receiving code looks like this:

            window.addEventListener('message', function(e) {
                if (window === e.source) {
                    // ignore browser extensions that are sending messages.
                    return;
                }

                if (typeof e.data !== 'string') {
                    return;
                }

                var result = calculateSessionStateResult(e.origin, e.data);
                e.source.postMessage(result, e.origin);
            }, false);

The problem is that running in htmlunit, the window === e.source check is true and hence it doesn’t go on to process the message.

Running in Safari the same site works fine.

Adding some debug it seems event.source.location is the url for the page containing the receiving code.

Looking at the code here:

https://github.com/HtmlUnit/htmlunit/blob/96369779a836e3908aed9e6fa5acd3a54778c01e/src/main/java/org/htmlunit/javascript/host/Window.java#L1988

in particular:

    public void postMessage(final Object message, final String targetOrigin, final Object transfer) {
        final WebWindow webWindow = getWebWindow();
        final Page page = webWindow.getEnclosedPage();
        final URL currentURL = page.getUrl();

        if (!"*".equals(targetOrigin) && !"/".equals(targetOrigin)) {
<...>
        }

        final MessageEvent event = new MessageEvent();
        final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
        event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", this, transfer);
        event.setParentScope(this);
        event.setPrototype(getPrototype(event.getClass()));

I think ‘this’, which is used as ‘source’ is the target window rather than the source window? Certainly that seems to be what I’m seeing in the debugger.

About this issue

  • Original URL
  • State: closed
  • Created 10 months ago
  • Comments: 17 (10 by maintainers)

Commits related to this issue

Most upvoted comments

Great, thanks a lot for providing all the details (and for using HtmlUnit). As usual i will inform on twitter (https://twitter.com/htmlunit) about new releases

and ⭐ 's are also always welcome…

No need for a new issue, and i think i know the root of that problem.

sorry you have to be a bit more patient, the fix requires more time to adjust the tests

ok, will try to update the snapshot tomorrow

@jogu will have a look