以下是代码:
function fil(val) {
console.log('fil'); // never written to console when run in greasemonkey
return true;
}
var temp = unsafeWindow.someobject;
console.log(temp); // looks fine
temp.filter(fil); // never happens in greasemonkey
如果我在firebug控制台中的同一个对象上运行完全相同的代码(当然没有unsafeWindow),它输出就好了。可能是什么原因?
编辑澄清:当在greasemonkey中运行时,字符串'fil'永远不会被写入控制台,这表明永远不会调用fil()。此外,如果我执行类似console.log(temp.filter(fil));
的操作,当代码从greasemonkey运行时,我永远不会从控制台中看到结果。 (虽然我知道它应该是因为上面的行告诉我temp
存在且代码运行到那一点。
答案 0 :(得分:0)
就我而言,在Firefox 45和Greasemonkey 3.7中,此代码可以正常工作:
// ==UserScript==
// @name Array.prototype.filter() test
// @namespace http://stackoverflow.com/questions/33675675/
// @include http://stackoverflow.com/questions/33675675/*
// @version 1.0
// @grant none
// ==/UserScript==
function fil(val) {
console.log('fil'); // never written to console when run in greasemonkey
return true;
}
var temp = unsafeWindow.allowedHosts;
console.log(temp); // looks fine
temp.filter(fil); // never happens in greasemonkey
输出:
Array [ "stackoverflow.com", "serverfault.com" ]
fil
fil
但是将none
更改为例如GM_getValue
行:
// @grant none
仅输出:
Array [ "stackoverflow.com", "serverfault.com" ]
这是因为传递给@grant
除了none
之外的任何值都启用了沙箱,而且从我所看到的情况来看,包装的对象不支持将回调函数作为参数的方法。
您可以使用上面链接中的兼容性层替换某些GM_*
权限。然后,您可以通过设置@grant none
来禁用沙盒,并且您已完成设置。
但是,如果您需要原始功能,则可以使用[].filter.call(temp, fil)
代替temp.filter(fil)
,如评论中所述。