Search code examples
javascriptfirefoxxpcom

Can you check if an object is wrapped by XPConnect (Firefox)?


My scenario: I am iterating over the window object and trying to retrieve only user-defined variables/functions and filtering out native browser objects.

for(var i in window) {
    // Right now I just have a bunch of if checks on window[i]
}

I noticed that native browser objects/XPCOM components are wrapped via XPConnect which returns a wrapper of the object that allows it to interface with Javascript. I am thinking that if I could somehow check and see if the object is a wrapper then I can filter it out. Is there a way to check if an object is wrapped via XPConnect? I would like to filter out all objects that are wrapped as any of the wrapper types listed here: https://developer.mozilla.org/en/XPConnect_wrappers


Solution

  • You can detect an XPCWrappedNative because x instanceof Components.interfaces.nsISupports returns true. However, this also returns true for DOM nodes, documents, windows etc. If this isn't what you want, a subsequent x.QueryInterface(Components.interfaces.nsIClassInfo) should succeed for most DOM objects.

    You can't detect an XPCWrappedJS unless the underlying JS object exposes the wrappedJSObject property. (You don't actually see the XPCWrappedJS object itself, since that's a C++ object, but that object could then get passed back into JS as an XPCWrappedNative.)

    You can detect an XPCNativeWrapper using x == XPCNativeWrapper(x). The underlying object will itself be an XPCWrappedNative, of course.

    You can't really detect an XPCSafeJSObjectWrapper, you just have to know that if you unwrap an XPCNativeWrapper for a content object then you will get an XPCSafeJSObjectWrapper.