views:

974

answers:

3

Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript.

So, to be more specific, given node x, I need to find the specific window object that contains x.

+2  A: 

You may want to use self. self is a reference to the current document.

From within the iframe:

<body>
<div id="example">Example!</div>
<script type="text/javascript">
    window.onload = function () {
        var exampleNode = document.getElementById('example');
        exampleNode.bar = function () {
            // The highest window object:
            top;
            // The parent node:
            self;
            // The parent node ( except in IE );
            this.ownerDocument.defaultView;
        };
    };
</script>
</body>

Traversing Multiple Window Objects:

Within the browser object model, the primary window object is referred to as top. Other global objects are arranged in a tree structure which stems from top. With a reference to top, you can navigate to the other global objects in the tree by using their names and relationships, much in the same way as you traverse the DOM.

When you have multiple window objects, as you do in the case of an iframe (of with old school framesets), the frame has a name attribute. Given the objects position relative to the top window object, you can use the name of the child to access the object.

<iframe src ="/default.html" name="advertisement"></iframe>

and then from the context of the top window:

self.advertisement

keparo
+3  A: 

I found the combination of properties I was after:

node.ownerDocument.defaultView

That returns the window object that the node belongs to. Note that this does not work in IE.

Joel Anair
node.ownerDocument.defaultView is the standard way to do it. That will work on web pages in Safari and Opera too.
Shadow2531
+1  A: 

+1 to your question, it was exactly what I was looking for and thanks for the hint given directly by answering yourself.

I Googled a bit and according to http://www.quirksmode.org/dom/w3c_html.html cross-browsers tables I think the right answer is:

function GetOwnerWindow(html_node)
{
   /*
   ownerDocument is cross-browser, 
   but defaultView works on all browsers except Opera/IE that use parentWinow
   */
   return (html_node.ownerDocument.defaultView) ?
      html_node.ownerDocument.defaultView : 
      html_node.ownerDocument.parentWindow;
}

Or maybe even better:

return html_node.ownerDocument.defaultView || html_node.ownerDocument.parentWindow;

Plz let me know your thoughts.

Marco Demajo
Awesome. Thanks for the additional information.
Joel Anair