How can I get the window object that an HTML node belongs to using JavaScript?
Asked Answered
C

3

11

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.

Clingy answered 21/10, 2008 at 23:56 Comment(0)
R
15

+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.

Riffe answered 28/4, 2010 at 10:6 Comment(0)
S
3

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

Silvey answered 21/10, 2008 at 23:56 Comment(0)
C
3

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.

Clingy answered 22/10, 2008 at 0:13 Comment(1)
node.ownerDocument.defaultView is the standard way to do it. That will work on web pages in Safari and Opera too.Aconite

© 2022 - 2024 — McMap. All rights reserved.