2

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?

Mala
  • 14,178
  • 25
  • 88
  • 119

2 Answers2

2

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
  • 90,639
  • 22
  • 233
  • 295
  • 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 Jul 15 '10 at 19:26
  • @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 Jul 15 '10 at 22:43
  • Please do not encourage the use of unsafeWindow - it is named **unsafe** for a reason. – kwah Jul 02 '11 at 13:57
  • @kwah, `unsafeWindow` is **provided** for a reason. There are many cases when it is the correct or only approach. ... While it is true that an unscrupulous website could *theoretically* exploit the use of unsafeWindow to gain *slightly* elevated privileges... (1) The script author will be able to ID sites that might try such tricks and is forewarned. (2) The odds are very low. The cost/benefit ratio of a webmaster, attempting this exploit, means it will never be used except, maybe, in extreme cases. (3) There are **zero** documented cases of an exploit in the wild and the test case 404's out. – Brock Adams Jul 06 '11 at 00:34
0

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())";
kwah
  • 1,149
  • 1
  • 13
  • 27