[Greasemonkey] Calling a function in GM from injected HTML

Anthony Lieuallen arantius at gmail.com
Fri Aug 4 15:07:07 EDT 2006


On 8/4/2006 1:52 PM, IndaUK wrote:
> <a href="javascript:RemoveGroup('Foo')">[-]</a>
>...
> Why do I get a "RemoveGroup is not defined" error when I click the link?

The long and the short of it is that GM scripts execute in their own 
(security related) scope.  When the (GM) script stops running, the scope 
disappears, along with everything inside it.  *UNLESS* there is still a 
reference to it somewhere.  A string "javascript:RemoveGroup..." is not 
a javascript object reference.

It is the same reason this doesn't work:

(function() {
var x=10;
})();
alert(x);

Will say that x is not defined.  That (anonymous) function is its own 
scope.  Once the function ends, the scope is gone, as is the variable X 
inside it.  The way you do what you want above is (greasemonkey code here):

var anchor=document.getElementById('foo'); // get a refernence to the a
a.addEventListener('click', RemoveGroup, true);


More information about the Greasemonkey mailing list