css TamperMonkey中的GM_addStyle等效项

qybjjes1  于 2023-02-01  发布在  其他
关注(0)|答案(7)|浏览(295)

是否有一个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等价物,使我不必在每个脚本上重复这个过程?

fbcarpbf

fbcarpbf1#

版本4.0或+,2018年更新

ReferenceError: GM_addStyle is not defined

您需要创建自己的GM_addStyle函数,如下所示:

// ==UserScript==
// @name           Example
// @description    Usercript with GM_addStyle method.
// ==/UserScript==

function GM_addStyle(css) {
  const style = document.getElementById("GM_addStyleBy8626") || (function() {
    const style = document.createElement('style');
    style.type = 'text/css';
    style.id = "GM_addStyleBy8626";
    document.head.appendChild(style);
    return style;
  })();
  const sheet = style.sheet;
  sheet.insertRule(css, (sheet.rules || sheet.cssRules || []).length);
}

//demo :
GM_addStyle("p { color:red; }");
GM_addStyle("p { text-decoration:underline; }");

document.body.innerHTML = "<p>I used GM_addStyle.</p><pre></pre>";

const sheet = document.getElementById("GM_addStyleBy8626").sheet,
  rules = (sheet.rules || sheet.cssRules);

for (let i=0; i<rules.length; i++)
  document.querySelector("pre").innerHTML += rules[i].cssText + "\n";

已弃用

如果GM_addStyle(...)不起作用,请检查您是否有@grant GM_addStyle标头。

就像这样

// ==UserScript==
// @name           Example
// @description    See usercript with grant header.
// @grant          GM_addStyle
// ==/UserScript==

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

7vux5j2d2#

根据TamperMonkey文档,它像GreaseMonkey一样直接支持GM_addStyle检查包含/匹配规则是否正确,然后将以下演示代码添加到用户脚本的顶部:

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

我刚刚在Chrome 35中的一个新鲜用户脚本上测试了它,它按预期工作。如果你有任何其他@grant规则,你将需要为这个函数添加一个,否则它应该会被自动检测和授予。

3pvhb19x

3pvhb19x3#

如果有人感兴趣的话,我修改了代码,这样你就不必在每个css规则后面写“!important”了。当然,这只有在你使用这个函数而不是GM_addStyle的情况下才有效。

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.replace(/;/g, ' !important;');
    head.appendChild(style);
}

这个“addGlobalStyle('body { color: white; background-color: black; }');“的输出,
将是“body { color: white !important; background-color: black !important; }');

8yparm6h

8yparm6h4#

我也有同样的问题。我尝试了所有的修正,确保在头文件中有// @grant GM_addStyle。我的问题是,我也有默认代码的// @grant none在头文件的底部。删除了这一部分,现在我所有的css工作。希望这有助于其他人,如果他们也坚持这一点。

r3i60tvu

r3i60tvu5#

我有运行在各种引擎的GreaseMonkey脚本,这涵盖 * 所有 * 品种:

--snip--
// @include      *.someplace.com/*
// @grant        GM_addStyle
// ==/UserScript==

(function() {
  'use strict';

let myCSS=(<><![CDATA[
body { background: #121212 url(https://somewhere.github.io/boss/imgs/bg.jpg) top left repeat !important; }
]]></>).toString();

// workaround for various GreaseMonkey engines
if (typeof GM_addStyle != "undefined") {
    GM_addStyle(myCSS);
} else if (typeof PRO_addStyle != "undefined") {
    PRO_addStyle(myCSS);
} else if (typeof addStyle != "undefined") {
    addStyle(myCSS);
} else {
    var node = document.createElement("style");
    node.type = "text/css";
    node.appendChild(document.createTextNode(myCSS));
    var heads = document.getElementsByTagName("head");
    if (heads.length > 0) {
        heads[0].appendChild(node);
    } else {
        // no head yet, stick it whereever
        document.documentElement.appendChild(node);
    }
}

这段代码摘自2018年编写的一个脚本,已知它可以在GreasMonkey、TamperMonkey和ViolentMonkey(可能还有其他的)中工作。修改上面提到的addGlobalStyle(css)函数,你应该可以很好地去 * 任何地方 *。

guykilcj

guykilcj6#

我的2美分的主题,认为它可能是有趣的人,我修改了PaarCrafter的答案,允许多行没有括号:
用法:

addGlobalStyle`
    button.special {
        position: relative;
        top: -3em;
    }
`

// string templating ('Template literals') works anyways
addGlobalStyle(`p {
  color: red;
}`)

// Still works
addGlobalStyle('p {color: red;}')

修改版本:

function addGlobalStyle(css = '') {
    let target = documnet.head || document.body;
    let style = document.createElement('style');
    
    style.type = 'text/css';
    style.innerHTML = (css || arguments.length ? arguments[0][0] : '').replaceAll(';', ' !important;');
    target.append(style);
}
nbewdwxp

nbewdwxp7#

下面是https://userstyles.org使用的解决方案,例如,当您在https://userstyles.org/styles/23516/midnight-surfing-global-dark-style这样的样式页面上单击“将样式安装为用户脚本”链接时:

if (typeof GM_addStyle != "undefined") {
    GM_addStyle(css);
} else if (typeof PRO_addStyle != "undefined") {
    PRO_addStyle(css);
} else if (typeof addStyle != "undefined") {
    addStyle(css);
} else {
    var node = document.createElement("style");
    node.type = "text/css";
    node.appendChild(document.createTextNode(css));
    var heads = document.getElementsByTagName("head");
    if (heads.length > 0) {
        heads[0].appendChild(node);
    } else {
        // no head yet, stick it whereever
        document.documentElement.appendChild(node);
    }
}

注:代码将工作在Greasemonkey 4以及类似的插件。我不使用Tampermonkey,它不是开源的,但这个答案可能会帮助其他用户找到这个问题。它将尝试使用几个内置函数的不同插件之前,使用纯JavaScript解决方案。您可能只需要代码从else块。
如果您确定页面有head标签,则可能不需要检查head标签长度的“if”条件,您可以将节点添加到head,如下所示:但是我注意到有时会有一个JavaScript错误,根据使用的方法,头是未定义的或空的,例如在www.example.com上facebook.com注销时(至少在使用// @run-at document-start时,它是黑暗主题所必需的,以避免 Flink )。
如果你想使用多行CSS代码,你可以创建一个带有反勾的css变量,如下所示:

var css = `
CODE HERE
`;

更新:我刚刚看到这个解决方案也用在另一个答案中,但没有提到来源。

相关问题