Search code examples
javascripthtmlxsspostmessage

Can I compare the source window from postMessage to my window.frames?


I want to bubble some information from a frame to its parent object (information that isn't accessible due to XSS).

Can I compare the source window sent via postMessage to the values of window.frames?

MDN (in the link above) says that the message can be used to postMessage back but doesn't refer to testing for equality.

This works correctly on IE9 FF5 and Chrome12 but I want to know if this is dependable (i.e. is it in the standard).

Test code:

postMessageOuter.html

<!DOCTYPE html>
<html>
<head>
    <title>Outer Page</title>
    <script type="text/javascript">
        window.addEventListener("message", function (event) {
            for (var i = 0; i < frames.length; ++i)
                if (event.source == frames[i])
                    alert(i);
        }, false);
    </script>
</head>
<body>
<iframe src="postMessageInner.html"></iframe>
<iframe src="postMessageInner.html"></iframe>
<iframe src="postMessageInner.html"></iframe>
</body>
</html>

postMessageInner.html

<!DOCTYPE html>
<html>
<head>
    <title>Inner Page</title>
    <script type="text/javascript">
        function foo() {
            window.parent.postMessage("Hello", "*");
        }
    </script>
</head>
<body>
<input type="button" value="X" onclick="foo()" />    
</body>
</html>

Solution

  • postMessage is part of the HTML5 draft and thus supported in the newest browsers.

    The spec says

    the source attribute must be set to the script's global object's WindowProxy object

    this WindowProxy is the value of the window.frame enumeration, too.

    http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages