[Greasemonkey] Using functions in JavaScript Includes

Jeremy Dunck jdunck at gmail.com
Thu Aug 18 11:41:23 EDT 2005


On 8/18/05, Richard Wallis <Richard.Wallis at talis.com> wrote:
> Hi,
> 
> I want to be able to reuse a set of functions in several Greasemonkey
> scripts.  To keep things simple I want to create a utils.js script file
> to keep them in and then load that file in each xx.user.js.
> 
> For test purposes here is the contents of utils.js:
> 
> //GM_log("Hi");
> function fun1(){
>         //GM_log("F1");
> 
>         alert("<H1>Hello world</H1>");
> }
> 
> I would expect that document.write("<script
> type='application/x-javascript'
> src='http://myserver.com/scripts/utils.js'></script>"); would load the
> file for me.  I know it does because if I uncomment the GM_log() I get a
> not defined error.
> 
> If I try to call fun1(); from my .user.js script I get a not defined
> error.
> 
> Any ideas if what I want to do is possible, and if it is what is my
> problem.

When you append a script elm, you're in the content context, which is
intentionally separate from the GM context (for security reasons). 
The GM API is not available in the page context.  You're encouraged to
-not- add the GM API functions to the page context, either.

Consider writing your library functions to use callbacks, like so:

GM code:
====
//inject library script elm here...
//...later...
DoStuffWithGM('waka', GM_log);


Library code:
=====
function DoStuffWithGM(param1, gmapifunc) {
  gmapifunc('foo!');
}


More information about the Greasemonkey mailing list