1

我需要为greasemonkey 编写一个脚本,用一个每次都返回true 的方法覆盖默认的document.hasFocus。

这是我尝试使用的代码:

var script = document.createElement('script');
script.type = "text/javascript";
script.innerHTML = 'function document.hasFocus{return true;}';
document.getElementsByTagName('head')[0].appendChild(script);

但它不起作用...

任何想法?

谢谢

4

1 回答 1

1

语法关闭,可能没有<head>标签。此外,尽可能避免使用innerHTML。所以使用:

var scriptNode          = document.createElement('script');
scriptNode.type         = "text/javascript";
scriptNode.textContent  = 'document.hasFocus = function () {return true;}';
var targ                = document.getElementsByTagName ('head')[0] || document.body;
targ.appendChild (scriptNode);

unsafeWindow但是,在这种情况下,使用(Firefox Greasemonkey)的风险很小。所以整个脚本代码可能是:

unsafeWindow.document.hasFocus = function () {return true;};

如果它仍然“不起作用”,请描述它是如何不起作用的(预期结果与实际结果;错误代码等)。链接到目标页面。

于 2012-06-29T23:29:03.840 回答