|User Script Authoring|
|Other Useful Tools|
Why a Special Environment?
When Greasemonkey executes a user script it does so in a special sandbox environment. Greasemonkey takes advantage of a Firefox feature called XPCNativeWrappers to insulate the user script from the content web page, which it references.
Although this makes it more difficult, or impossible, to do certain things in a script, it is a necessary evil. Earlier versions of Greasemonkey had no such sandbox, and as a result, security holes were uncovered.
Luckily, for almost all the difficulties that the sandbox environment provides, there are ways to still accomplish the desired goal. The article Avoid Common Pitfalls in Greasemonkey does a wonderful job explaining what the most common snags are, and for each one explains the way to work around the problem. It is essential reading for any script author.
Depending on the usage, the special Greasemonkey environment may seem perfectly normal, or excessively limiting.
The Greasemonkey environment is a vanilla XPCNativeWrapper of the content window, with only certain extra bits added in to emulate a normal environment, or changed. Specifically:
windowis an XPCNativeWrapper of the content window.
documentis the document object of the XPCNativeWrapper window object.
- XPathResult is added so that
varvariable declarations made (e.g.
var i = 5;) into the function's local scope. Declarations made without
varwill however end up on the script's
thisobject, which in Greasemonkey is the global object, contrary to in the normal browser object model, where the
windowobject fills this function. In effect, after
i = 5;, the values of
window.iremain undefined, whereas
this.iwill be 5. See also: Global object
- In order to access variables on the page, use the unsafeWindow object. To use values defined in a script, simply reference them by their names.
Since Mozilla provides a rich environment, there are a wide variety of things that have not been imported from the general content scope into the Greasemonkey sandbox. Including, but not limited to:
The more esoteric the method, the less likely that it has been included in the Greasemonkey sandbox.