小书签中的代码可在控制台中使用,但不能在我的Tampermonkey脚本中使用? [英] Code from bookmarklet works in console but not in my Tampermonkey script?

查看:141
本文介绍了小书签中的代码可在控制台中使用,但不能在我的Tampermonkey脚本中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请勿在Userscript中使用外部库的动态注入.改为@require.

Don't use exotic dynamic injection of external libraries in Userscript. @require them instead.

我正在尝试使用以下脚本修改此页面:

I am trying to modify this page with the following script:

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中的同一脚本不起作用(并且控制台中显示调试行,表明该脚本确实正在运行):

The script works fine from the console (try it), transforming window-open links to URL hrefs. However, the same script in Tampermonkey does not work (and the debug line shows in the console, indicating that the script is indeed running):

这些是特定脚本的设置:

These are the settings for the particular script:

我在做什么错?如何通过Tampermonkey使脚本起作用?

检查语法后(请参见注释):

After checking syntax (see comments):

将逗号替换为分号---这真是一团糟.

Changing some commas to semicolons --- this is a mess.

推荐答案

该脚本依靠非常短的计时器来加载jQuery.那是非常糟糕的形式.它设置了一种竞赛条件,在一种情况下可能还可以,但在其他情况下却无法通过.

That script relies on a very short timer for jQuery to load. That is very bad form; it sets up a race condition which might be okay in one circumstance but fail in others.

(大多数)它可以在控制台上正常工作,因为大多数代码都是同步运行的,并且都在同一范围内.

It might (usually) work from the console because most of the code operates synchronously and it's all in the same scope.

但是Tampermonkey脚本中的代码切换范围并注入一些而非全部所需的代码.

But that code from a Tampermonkey script switches scopes and injects some but not all of the needed code.

不要那样使用用户脚本中的jQuery !将脚本保留在沙盒中,并使用@require以获得更好的性能.

Don't use jQuery from a userscript that way! Keep the script sandboxed and use @require for better performance.

在这种情况下,您的整个脚本将变为:

In this case, your entire script would become:

// ==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]
} );

这篇关于小书签中的代码可在控制台中使用,但不能在我的Tampermonkey脚本中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆