Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Window object from the Document object?

I can get window.document but how can I get document.window? I need to know how to do this in all browsers.

like image 891
Joren Avatar asked Aug 27 '09 00:08

Joren


People also ask

What is window object and document object?

The window object represents an open window in a browser. If a document contain frames (<iframe> tags), the browser creates one window object for the HTML document, and one additional window object for each frame.

How is the window object created?

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc.


4 Answers

You can go with document.defaultView if you’re sure its a window and its okay to skip Microsoft browsers before IE 9.

like image 84
kennebec Avatar answered Oct 26 '22 06:10

kennebec


A cross browser solution is complicated, here's how dojo does it (from window.js::get()):

// In some IE versions (at least 6.0), document.parentWindow does not return a
// reference to the real window object (maybe a copy), so we must fix it as well
// We use IE specific execScript to attach the real window reference to
// document._parentWindow for later use
if(has("ie") && window !== document.parentWindow){
    /*
    In IE 6, only the variable "window" can be used to connect events (others
    may be only copies).
    */
    doc.parentWindow.execScript("document._parentWindow = window;", "Javascript");
    //to prevent memory leak, unset it after use
    //another possibility is to add an onUnload handler which seems overkill to me (liucougar)
    var win = doc._parentWindow;
    doc._parentWindow = null;
    return win; //  Window
}

return doc.parentWindow || doc.defaultView; //  Window

has("ie") returns true for IE (and false otherwise)

like image 35
Bill Keese Avatar answered Oct 26 '22 04:10

Bill Keese


Well, this is the solution I went with. It works, but I hate it.

getScope : function(element) {
    var iframes = top.$$('iframe');
    var iframe = iframes.find(function(element, i) {
        return top[i.id] ? top[i.id].document == element.ownerDocument : false;
    }.bind(this, element));
    return iframe ? top[iframe.id] : top;
}   
like image 43
Joren Avatar answered Oct 26 '22 05:10

Joren


I opted to inject the DOCUMENT token from @angular/platform-browser:

import { DOCUMENT } from '@angular/platform-browser'

and then access the parent:

constructor(@Inject(DOCUMENT) private document: any) {
}

public ngOnInit() {
  // this.document.defaultView || this.document.parentWindow;
}
like image 42
Jack Avatar answered Oct 26 '22 04:10

Jack