views:

96

answers:

1

I read "Dive into Greasemonkey" written in 2005. It mentions that Greasemonkey wraps a user script in an anonymous function wrapper. Does Greasemonkey insert the wrapper into the source JavaScript code or add it as any event handler such as window.onload?

+2  A: 

Does Greasemonkey insert the wrapper into the source JavaScript code or add it as any event handler such as window.onload?

GM listens to DOMContentLoaded event (basically DOM Ready) here. Then wraps the userscript code and inserts that into a sandbox, here.

Erik Vold
@Erik, thanks for pointing to the code. when the DOMContentLoaded event is fired, is the wrapper of the userscript invoked as the handler of the event or is the wrapper inserted as a part of the source code? in other words, line 309, this.evalInSandbox("(function(){"+ scriptSrc +"})()", url, sandbox, script), executes the wrapper or inserts the wrapper to the original javascript code?
Paul
First GM listens for DOMContentLoaded events, when those happen GM determines which userscripts should be run (via the @include/@exclude rules, and checking that the url is 'greasemonkeyable'), then source code from a userscript (which is just a string at this point) that should be run is wrapped in to an anonymous self executing function (via string concatenation), and finally does a evalInSandbox on the anonymous self executing function (which runs the userscript).
Erik Vold
So the script is executed at the time when it is injected. Is it correct?
Paul
yes, which is at DOMContentLoaded
Erik Vold