[Greasemonkey] How the script injection works and scoping questions

Aaron Boodman zboogs at gmail.com
Thu Apr 21 00:38:18 EDT 2005


First of all, it is hacky. You won't get a defense from me except for
to say that I don't have a ton of time for GM, so I use what works
without much prejudice. If you have improvements I'm happy to hear em.

On 4/20/05, Julien Couvreur <julien.couvreur at gmail.com> wrote:

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

So we'd pass the literal string of HTML to the page (somehow) and it
would eval it, yes? I have heard some horror stories that eval can
leak pretty badly with large chunks ofcode. I think that's the main
reason I avoided it. Also, eval always seems like a hack and last
resort to me.

> 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
> "GM_getValue.('test')".

What would the local variables resolve to? They have to point to
something! Content cannot get  access to chrome, so it has to be the
other way 'round: chrome has to provide the references to content
somehow. Note that the functions have to be actual objects which are
passed to content, not source code since source code, when interpreted
would not be allowed (security wise) to do the things that GM_*
functions do. So I don't think that a purely local variable method
would work.

But I do agree that scoping by locals is the way to go, which is why I
just use the window object as a temporary location and immediately
remove the references.

As far as using some fancy scoping with eval( ) or the with statement,
that is something I didn't think of much. Generally, I shy away from
"with" since it can really screw you and cause hard to debug errors,
particularly with variable creation. But maybe having var statements
show up on the with object instead of window is not such a bad thing
for GM.

> 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.

Well not really. The only specialness is that errors in one <script>
do not stop subsequent <script> tags from running. But that could be
easily simulated with try/catch.

-- 
Aaron


More information about the Greasemonkey mailing list