javascript:从 GM 脚本调用嵌入函数
在网页上
<script>
function fn982734()
{
// some code
}
</script>
,在我的 Greasemonkey 脚本中,我有以下代码:
var fn = fields[5].getElementsByTagName("a")[0].getAttribute('onclick').substr(7,11);
console.log(fn); // outputs fn982734 to the firebug console
window[fn]();
此代码不起作用,并在错误控制台中生成错误: window[fn] 不是函数。然而,直接输入 firebug:
var fn = 'fn982734';
window[fn]();
效果很好。这是怎么回事?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Greasemonkey 脚本位于沙箱内,而 Firebug 则不在沙箱内。
请参阅:“避免常见陷阱”(在 Greasemonkey 中)。
您的 GM 脚本将通过
unsafeWindow
访问该函数。像这样:.
或者,
也可以在 Greasemonkey 脚本内部工作。
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,
Also works -- from inside the Greasemonkey script.
我意识到我回答这个问题有点晚了,但请不要鼓励使用 unsafeWindow - 它被命名为 unsafe 是有原因的。
正确的替代方案是使用 Greasemonkey's Greasepot Wiki 中所述的“位置黑客”。此代码应正确调用原始帖子中描述的函数:
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: