在网页上有
<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]();
完美无缺。发生了什么事?
答案 0 :(得分:2)
Greasemonkey脚本位于沙箱内,而Firebug则不是。 请参阅:"Avoid Common Pitfalls" (in Greasemonkey)。
您的GM脚本将通过unsafeWindow
访问该功能。像这样:
unsafeWindow.fn982734();
。
或者,
var fn = 'fn982734';
unsafeWindow[fn]();
同样有效 - 来自Greasemonkey脚本。
答案 1 :(得分:0)
我意识到我对这个问题有些迟,但请不要鼓励使用unsafeWindow - 因为某种原因,它被命名为 unsafe 。
正确的选择是使用Greasemonkey's Greasepot Wiki中描述的“位置黑客”。此代码应正确调用原始帖子中描述的函数:
location.href = "javascript:void(fn982734())";