Skip to content

Incorrect event.source when using postMessage #633

@jogu

Description

@jogu

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:

final URL currentURL = page.getUrl();

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions