[Greasemonkey] Can anybody explain to me the strange namespace rule?

esquifit esquifit at googlemail.com
Tue Jun 6 21:38:53 EDT 2006


Userscripts execute in a temporary context that ceases to exist when the
page is loaded.  Any function defined in the script is then no longer
available from the page unless a reference to this function is passed to it.

When you do

unsafeWindow.self_defined_function= function() {...}

you are passing a reference to 'self_defined_function' to the page context
(unsafeWindow); the second function, 'another_function' would normally not
be available from the loaded page, but you are encapsulating a reference to
it in 'self_defined_function', so that mozilla does not destroy
another_function until no references to it are left.

Regardless of that, I think there are better ways to accomplish what your
are trying to do, namely, by using the preferred way to attach behaviour to
a DOM element: through the addEventListener method.  This has the advantage
that the page cannot override your function because the context in which
self_defined_function was declared is not available to page content.

var alink=document.createElement('A');
alink.innerHTML='A link';
alink.href="javascript:return false;";
self_defined_function=function(){
    alert('foo');
};

alink.addEventListener ('click',self_defined_function,false);

document.body.appendChild(alink);

Note: true, the 'alink.href="javascript:return false;"' is really ugly; it
is there to avoid reloading the page after clicking on the link; href="#"
would also do, but it repositions the page at the top.

With this approach you are passing a reference to self_defined_function to
the page context.

2006/6/5, Linan Wang < tali.wang+maillist at gmail.com >:
>
> I noticed that in greasemonkey scripts, to add a link in a page call a
> self
> defined function, have to 'hook' the function into the unsafeWindow. For
> example:
>
> var alink=document.createElement('a');
> a.innerHTML='A link';
> a.href='javascript:self_defined_function()';
>
> unsafeWindow.self_defined_function=function (){
>      another_function();
> };
>
> function another_function(){}
>
> It is understandable, but in the 'self_defined_function', if i want to
> call
> another function defined in userscript, that function should NOT be hooked
>
> into unsafe. Why? Can anybody explain to me?
>
> Many thanks!
>
> Best regards
>
> Linan Wang
> _______________________________________________
> Greasemonkey mailing list
> Greasemonkey at mozdev.org
> http://mozdev.org/mailman/listinfo/greasemonkey
>


More information about the Greasemonkey mailing list