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

前端 未结 6 1691
太阳男子
太阳男子 2021-01-01 08:29

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

6条回答
  •  孤独总比滥情好
    2021-01-01 09:03

    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)

提交回复
热议问题