[Greasemonkey] How the script injection works and scoping questions

Julien Couvreur julien.couvreur at gmail.com
Thu Apr 21 00:09:52 EDT 2005

Forked from the "Long literal strings of html", to discuss the gory
details of the script injection.

I was asking about the "injectScript" function: How come we're setting
these GM_* on the windows object? "greaseLoad" actually deletes these
references later. But I don't understand why we need to set them in
the first place.

Edward replied:
> Putting the functions in window provides a middleground for the
> extension to pass stuff to scripts on the page.

I understand how the window object is used as a temporary storage for
the methods, so they can be picked up by the injected script. But it
doesn't seem like the simplest way.

Looking into some more details into how the injection works: 
          function runBrowserScript(doc, jscode) {
            var elm = doc.createElement("SCRIPT");

We're adding a script node (that gets evaluated) and then the node is
cleaned up. Also seems hacky.

Why aren't we doing "eval"? That would make both functions
("injectScript" and "runBrowserScript") cleaner.

Could the injection work the following way:
We could have local variables with all those GM_* methods (instead of
temporarily storing them in the "window" object), then run the
injected script with eval.
The injected script would see the GM_* methods as any other variable
in scope. It could call them thru direct call, such as

If the script evaluated as part of <script> tags is treated any
special way (with a specific scope related to the document being
evaluated), we can just re-create the same conditions for the "eval"
call, maybe using the "with" statement.

Am I smoking? ;-)

More info about "with" statement in javascript/ECMAscript:

More information about the Greasemonkey mailing list