是否有一个TamperMonkey等效于GreaseMonkey的GM_addStyle
方法来添加CSS?
在GreaseMonkey中,您可以向多个元素添加一组CSS属性,如下所示:
GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");
要在TamperMonkey中执行相同的操作,我目前必须执行以下操作:
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
}
addGlobalStyle('body { color: white; background-color: black; }');
这是可行的,但是是否有一个内置的tamperMonkey的GM_addStyle
等价物,使我不必在每个脚本上重复这个过程?
7条答案
按热度按时间fbcarpbf1#
版本4.0或+,2018年更新
您需要创建自己的GM_addStyle函数,如下所示:
已弃用
如果
GM_addStyle(...)
不起作用,请检查您是否有@grant GM_addStyle
标头。就像这样
7vux5j2d2#
根据TamperMonkey文档,它像GreaseMonkey一样直接支持
GM_addStyle
。检查包含/匹配规则是否正确,然后将以下演示代码添加到用户脚本的顶部:我刚刚在Chrome 35中的一个新鲜用户脚本上测试了它,它按预期工作。如果你有任何其他
@grant
规则,你将需要为这个函数添加一个,否则它应该会被自动检测和授予。3pvhb19x3#
如果有人感兴趣的话,我修改了代码,这样你就不必在每个css规则后面写“!important”了。当然,这只有在你使用这个函数而不是GM_addStyle的情况下才有效。
这个“
addGlobalStyle('body { color: white; background-color: black; }');
“的输出,将是“
body { color: white !important; background-color: black !important; }');
“8yparm6h4#
我也有同样的问题。我尝试了所有的修正,确保在头文件中有
// @grant GM_addStyle
。我的问题是,我也有默认代码的// @grant none
在头文件的底部。删除了这一部分,现在我所有的css工作。希望这有助于其他人,如果他们也坚持这一点。r3i60tvu5#
我有运行在各种引擎的GreaseMonkey脚本,这涵盖 * 所有 * 品种:
这段代码摘自2018年编写的一个脚本,已知它可以在GreasMonkey、TamperMonkey和ViolentMonkey(可能还有其他的)中工作。修改上面提到的
addGlobalStyle(css)
函数,你应该可以很好地去 * 任何地方 *。guykilcj6#
我的2美分的主题,认为它可能是有趣的人,我修改了PaarCrafter的答案,允许多行没有括号:
用法:
修改版本:
nbewdwxp7#
下面是https://userstyles.org使用的解决方案,例如,当您在https://userstyles.org/styles/23516/midnight-surfing-global-dark-style这样的样式页面上单击“将样式安装为用户脚本”链接时:
注:代码将工作在Greasemonkey 4以及类似的插件。我不使用Tampermonkey,它不是开源的,但这个答案可能会帮助其他用户找到这个问题。它将尝试使用几个内置函数的不同插件之前,使用纯JavaScript解决方案。您可能只需要代码从else块。
如果您确定页面有head标签,则可能不需要检查head标签长度的“if”条件,您可以将节点添加到head,如下所示:但是我注意到有时会有一个JavaScript错误,根据使用的方法,头是未定义的或空的,例如在www.example.com上facebook.com注销时(至少在使用
// @run-at document-start
时,它是黑暗主题所必需的,以避免 Flink )。如果你想使用多行CSS代码,你可以创建一个带有反勾的css变量,如下所示:
更新:我刚刚看到这个解决方案也用在另一个答案中,但没有提到来源。