javascript: call an embedded function from a GM script

On a webpage there's

  function fn982734()
     // some code

In my Greasemonkey script, I have the following code:

var fn = fields[5].getElementsByTagName("a")[0].getAttribute('onclick').substr(7,11);
console.log(fn); // outputs fn982734 to the firebug console

This code does not work, and spawns an error in the error console: window[fn] is not a function. However, typing directly into firebug:

var fn = 'fn982734';

works perfectly. What's going on?


The Greasemonkey script is inside a sandbox and Firebug is not. See: "Avoid Common Pitfalls" (in Greasemonkey).

Your GM script would access that function via unsafeWindow. Like so:


. Alternatively,

var fn = 'fn982734';

Also works -- from inside the Greasemonkey script.

I realise that I'm a little late to this question but Please do not encourage the use of unsafeWindow - it is named unsafe for a reason.

The correct alternative would be to use the "location hack" as described on Greasemonkey's Greasepot Wiki. This code should correctly call the function described in the original post:

location.href = "javascript:void(fn982734())";

Need Your Help

How to set build agent priority in TeamCity?

teamcity teamcity-9.0

I have two agents that can build my configuration.

EJB - Lookup failed for 'ejb/BookRequestBean'

java java-ee ejb ejb-3.0 glassfish-3

I am new to EJB, and was trying "Hello World" type of EJB Java program. Here is my EJB: