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
2010-07-15 00:31:56
@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
2010-07-15 01:02:20
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
2010-07-15 18:26:33
So the script is executed at the time when it is injected. Is it correct?
Paul
2010-07-15 20:13:37
yes, which is at DOMContentLoaded
Erik Vold
2010-07-15 21:38:12