长话短说
不要在 Userscript 中使用外部库的异常动态注入(inject)。 @require
代替它们。
原始问题
我正在尝试修改 this page使用以下脚本:
console.log("run");
!function(){var e=document.createElement("SCRIPT")
e.src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js",e.type="text/javascript",document.getElementsByTagName("head")[0].appendChild(e)
var t=function(e){window.jQuery?e(jQuery):window.setTimeout(function(){t(e)},100)}
t(function(e){e(".title").children().each(function(){this.href="/"+this.href.split("'")[1]})})}()
该脚本在控制台中运行良好(试试吧),将窗口打开的链接转换为 URL href
。但是,Tampermonkey 中的相同脚本不起作用(调试行显示在控制台中,表明脚本确实在运行):
这些是特定脚本的设置:
我做错了什么?如何使脚本在 Tampermonkey 中运行?
检查语法后(见评论):
将一些逗号更改为分号 --- 这是一团糟。
最佳答案
该脚本依赖于一个非常短的计时器来加载 jQuery。那是非常糟糕的形式;它设置了一个竞争条件,在一种情况下可能没问题,但在其他情况下可能会失败。
它可能(通常)在控制台工作,因为大部分代码同步运行,并且都在同一范围内。
但是来自 Tampermonkey 脚本的代码 switches scopes and injects一些但不是全部所需的代码。
不要use jQuery from a userscript那样!保持脚本沙盒化并使用 @require
以获得更好的性能。
在这种情况下,您的整个脚本将变为:
// ==UserScript==
// @name OpenHymnal fix
// @match http://openhymnal.org/genindex.html
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
console.log ("run");
$(".title").children ().each (function () {
this.href = "/" + this.href.split("'")[1]
} );
关于javascript - 来自 bookmarklet 的代码在控制台中有效,但在我的 Tampermonkey 脚本中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23923992/