XPCNativeWrapper
From GreaseSpot
Contents |
[edit] Overview
Most all objects on a target web page that a user script sees are wrapped in XPCNativeWrapper. The reason for this is so that a script can change the properties of an object (actually the wrapper) without any javascript on the target page being able to see it. Mostly the wrapping is "transparent" - wrapped and unwrapped objects seem to behave the same because the wrapping object passes methods to the wrapped object, though there are some some exceptions.
[edit] wrappedJSObject
For a script to access the real underlying object there is the method
var realObj = wrappedObj.wrappedJSObject;
Be very careful when using the wrappedJSObject property. It is just as dangerous as unsafeWindow is.
[edit] Security
Related to security.
- http://kb.mozillazine.org/XPCNativeWrapper
- http://developer.mozilla.org/en/docs/XPCNativeWrapper
- http://dunck.us/collab/GreaseMonkeyUserScripts#head-4ac4d1e80f8bbd66bf4f1fbea77ea2390b6a2870
Throughout the rest of this article, the term "XPCNativeWrappers" will often be abbreviated to "XPCNWs".
[edit] Limitations / Problems
[edit] Expando Properties
Expando Properties do not work on XPCNWs. This means that, for example, this will not work:
var el=document.createElement('a');
el.onclick='alert("Error"); return false;'
Instead, use setAttribute and addEventListener methods. Note the use of the preventDefault method to emulate the "return false" behavior above.
function showTheError(event) {
...
event.preventDefault();
}
var el=document.createElement('a');
el.addEventListener('click', showTheError, false);
This applies to any element, not just new ones you create (those references from createElement and those from getElementById et al), and any event handler, not just onclick.
[edit] for ... in on HTMLCollections
DOM methods like getElementsByTagName return HTMLCollections.
var arInputs = document.getElementsByTagName('input');
// does not work
for (var elmInput in arInputs) {
...
}
// does work
var elmInput;
for (var i=0; i < arInputs.length; i++) {
elmInput = arInputs[i];
...
}
[edit] Named Items
Items like frames, form elements, and so on can be referenced by name in normal JavaScript.
XPCNWs cannot reference items by name. Use the namedItem method.
With a <input name="foo"> in the form:
form.foo; // does not work
form.elements.namedItem('foo'); // works
The same goes for frames:
window.framename; // does not work window.frames['framename']; // works
[edit] Event Handlers
Normal JavaScript can access an element's event handlers with code like:
element.onclick = myClickHandler;
or
element.onclick = "myClickHandler(this)";
This does not work on XPCNWs; it will result in a "Component not available" error in the JavaScript console. Instead, use addEventListener:
element.addEventListener (myClickHandler);
Any Greasemonkey script written before version 0.5 was released in mid-2005 may need updating to use addEventListener.

