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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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: 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.
Please do not encourage the use of unsafeWindow - it is named unsafe for a reason.
@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.
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())";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.