javascript: call an embedded function from a GM script
On a webpage there's
&l开发者_JS百科t;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?
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.
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())";
精彩评论