many times I have had an issue and post for help and so many times QueryInterface is the solution. I have been addon programming for a long time now but never understood QueryInterface. It seems like magic, like it holds the solution to everything.
like:
window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
So my question is I see a QueryInterface chain, I don't get why the chain, and I definitely don't get how to create my own chain. I don't get how do you know to chain from nsiInterfaceRequester to nsiWebNavigation and not from nsiInterfaceRequester straight to nsiDOMWindow
There is really nothing special here. DOM windows implement the
nsIInterfaceRequestor
interface that allows getting related objects. One such object is the docshell that is associated with the window - you get it by asking for thensIWebNavigation
interface but it also implements thensIDocShell
andnsIDocShellTreeItem
interfaces - andnsIInterfaceRequestor
. The docshell for the current window lets you get to the docshell for the top window, despite the security boundary between chrome and content. And there you can use thensIInterfaceRequestor
interface again to ask the docshell for the window associated with it.You can simply implement the
nsIInterfaceRequestor
interface in your XPCOM component just like any other interface. I don't see any reason to ever do that however, it's an ugly hack to hide internal window-related interfaces from the DOM.