[Greasemonkey] evaluate and XPCNativeWrapper in 0.6.4
Mark Pilgrim
pilgrim at gmail.com
Tue Jan 31 10:42:14 EST 2006
On 1/31/06, Bruce Perry <bhrperry at comcast.net> wrote:
> I've bought "Greasemonkey Hacks" and I'm trying to get started with
> GreaseMonkey. I've installed GreaseMonkey 0.6.4 on Firefox 1.5. I'm
> trying to use XPath to get a collection of elements so that I can pull info
> from the elements.
>
> Here's the code:
>
> //get the page's h2 elements
> var snap = document.evaluate("//h2", document, null,
> XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
>
> for (var i = snap.snapshotLength - 1; i>=0; i--){
>
> var elm = snap.snapshotItem(i);
>
> alert('IT '+ elm +" " + elm.getAttribute('outerHTML'));
> }
First of all, document.evaluate is overkill for this application. If
you just want the h2 elements, use
var arHeaders = document.getElementsByTagName('h2');
for (var i = arHeaders.length - 1; i >= 0; i--) {
var elmHeader = arHeaders[i];
...
}
> This code gets the right number of elements and iterates through them. The
> variable 'elm' shows up in the alert box as '[object XPCNativeWrapper
> [object HTMLHeadingElement]]. If I try something like elm.outerHTML, the
> result is 'undefined'.
These issues are not actually related. The first is because, as noted
in Hack #12 -- online here:
http://www.oreillynet.com/pub/a/network/2005/11/01/avoid-common-greasemonkey-pitfalls.html
), everything you get through document.evaluate,
document.getElementById, document.getElementsByTagName, etc. is
wrapped in an XPCNativeWrapper. Normally these shouldn't affect you,
except that it's somewhat confusing during debugging when you
alert(elm) and see "[object XPCNativeWrapper]". You should be able to
access all of the normal attributes and methods without caring about
XPCNativeWrappers. There is a very small set of things that require
access to the underlying "unwrapped" object.
The second issue, as pointed out elsewhere in this thread, is because
outerHTML is an IE-proprietary attribute that Firefox doesn't emulate.
If you give us a better sense of what you're actually trying to do
with the h2 elements, perhaps we can suggest an alternative.
> Similar code in the "Zap Ugly XML Buttons" script works fine, but isn't
> trying to get anything out of the items that it's looping on. Can someone
> point me at an example of how to get data out of XPNativeWrapper items
> returned via XPath?
As I said, you should be able to access all of the supported
attributes and methods without caring that the element is "wrapped".
There is a way to access the "unwrapped" version, but this is
inherently unsafe (for reasons detailed in Hack #12), so I'm going to
be slightly patronizing and not tell you how to do it until you give
us more details on what you're trying to do. It is very likely that
you can do what you need without "unwrapping" each element.
--
Cheers,
-Mark
More information about the Greasemonkey
mailing list