问题
As in the question... how to get the window
object from an event fired in the window
scope for example:
handleEvent: function(event) {
// is window object available here and can we get it from event
}
I can get the window
object from other APIs. I was wondering if it was possible to get it from the fired event
.
Reference:
handleEvent
Code Snippet using handleEvent
回答1:
I found out the answer ... any of these will get the window
object from the event
event.view
event.viewevent.target.ownerDocument.defaultView
event.targetevent.originalTarget.ownerGlobal
event.originalTarget (Non-standard)
回答2:
It depends on the event. But most usually yes you can. Do a console.log on the event then you might something like targetChromeWindow or something, this one I can't remember i came across it once though while doing something.
Most usually though, get event.target or relatedTarget or originalTarget (theres one more target i forgot what it is) and do ownerDocument.defaultView
If you want the chrome window from that you can get that by doing this:
var DOMWin = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
回答3:
The following will populate the window and document variables if they do not already exist. It should work from any scope/context:
if (typeof window === "undefined") {
//If there is no window defined, get the most recent.
var window = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
}
if (typeof document === "undefined") {
//If there is no document defined, get it
var document = window.content.document;
}
Here are some additional variables which might be useful to have available, depending on what you are doing:
if (typeof gBrowser === "undefined") {
//If there is no gBrowser defined, get it
var gBrowser = window.gBrowser;
}
var tab = gBrowser.selectedTab;
var browserForTab = gBrowser.getBrowserForTab( tab );
var notificationBox = gBrowser.getNotificationBox( browserForTab );
var ownerDocument = gBrowser.ownerDocument;
来源:https://stackoverflow.com/questions/25979154/is-it-possible-to-get-the-window-object-from-the-event-in-handleevent