本文介绍了TamperMonkey中的GM_addStyle等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在与GreaseMonkey的添加CSS的 GM_addStyle 方法等效的TamperMonkey?

Is there a TamperMonkey equivalent to GreaseMonkey's GM_addStyle method for adding CSS?

在GreaseMonkey中,您可以向多个元素添加一堆CSS属性,如下所示:

In GreaseMonkey, you can add a bunch of CSS properties to multiple elements like so:

GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");

要在TamperMonkey中进行等效操作,我目前必须执行以下操作:

To do the equivalent in TamperMonkey, I'm currently having to do the following:

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 等效项,使我不必在每个脚本上都重复此操作?

This works, but is there a built-in GM_addStyle equivalent for TamperMonkey that saves me from having to repeat this on every script?

推荐答案

根据 TamperMonkey文档,它支持 GM_addStyle .检查您的包含/匹配规则是否正确,然后将此演示代码添加到用户脚本的顶部:

According to the TamperMonkey documentation, it supports GM_addStyle directly, like GreaseMonkey does. Check your include/match rules are correct, then add this demo code to the top of your userscript:

GM_addStyle('* { font-size: 99px !important; }');
console.log('ran');

我刚刚在Chrome 35中以全新的用户脚本对其进行了测试,它可以按预期工作.如果您还有其他 @grant 规则,则需要为此功能添加一个,否则应自动检测并授予它.

I just tested it on a fresh userscript in Chrome 35 and it worked as expected. If you have any other @grant rule, you will need to add one for this function, otherwise it should be detected and granted automatically.

这篇关于TamperMonkey中的GM_addStyle等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 21:49