views:

30

answers:

1

On a webpage there's

<script>
  function fn982734()
  {
     // some code
  }
</script>

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
window[fn]();

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';
window[fn]();

works perfectly. What's going on?

+3  A: 

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:

unsafeWindow.fn982734();

.
Alternatively,

var fn = 'fn982734';
unsafeWindow[fn]();

Also works -- from inside the Greasemonkey script.

Brock Adams
replacing 'window[func]();' with 'unsafeWindow[func]()' results in a File Not Found error: Firefox can't find the file at jar:file:///usr/lib/firefox-3.6.6/chrome/browser.jar!/content/browser/[uri]
Mala
@Mala: `var fn = 'fn982734'; unsafeWindow[fn]();` totally works, I double-checked to make sure. That error message also does not match the code shown. Paste the **EXACT** Greasemonkey code, and link to the target page.
Brock Adams