[Greasemonkey] Adding methods/properies to document object with GM

Lenny Domnitser ldrhcp at gmail.com
Wed Jul 20 16:15:30 EDT 2005


This specific case (calling alert) is not a security concern, but the
best practice is to keep objects in the user script scope.

What you are doing is inserting HTML that references Javascript you
define in the user script. A more elegant way to get the same
functinality is using Javascript "closures", which means the scope of
a function call is where the function is defined, not where it is
called from. When you set innerHTML, you are having your "onclick=..."
code parsed as HTML, and onclick is defined only then. If you define
onclick in the user script, you will have access to all user script
objects. Your example code can be rewritten to this:

var foo = 'bar';

function func(){
   window.alert(foo);
}

function initScript(){
               var div = document.createElement('div');
               var link = document.createElement('a');
               link.onclick = func; // that fancy closure thing
               link.appendChild(document.createTextNode('click me'));
               div.appendChild(link);
               var content = document.getElementById('content');
               content.parentNode.insertBefore(div,content.nextSibling);
}

window.addEventListener("load",initScript,false);

A few more notes:
* Don't put parentheses in the addEventListener function reference.
You want to pass the function, not the results of the function. You
can usually avoid waiting for the window load event, anyway, since
Greasemonkey executes when the DOM loads, but before onload.
* You may want to do something like link.href = 'javascript:;', so it
would be treated as a link, not a page anchor.


More information about the Greasemonkey mailing list