Вопрос

Is there a TamperMonkey equivalent to GreaseMonkey's GM_addStyle method for adding 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; }");

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; }');

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

Это было полезно?

Решение 2

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:

// ...
// @grant        GM_addStyle
// ==/UserScript==

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

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.

Другие советы

Version 4.0 or +, update of 2018

ReferenceError: GM_addStyle is not defined

You need to create your own GM_addStyle function, like this :

// ==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";

DEPRECATED

If GM_addStyle(...) doesn't work, check if you have @grant GM_addStyle header.

Like this :

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

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

If somebody is interessted, I changed the code so you don't have to write "!important" after every css rule. Of course this only works, if you use the function instead of 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);
}

The output of this "addGlobalStyle('body { color: white; background-color: black; }');",

will be "body { color: white !important; background-color: black !important; }');"

I was having this same issue. I tried all the fixes, making sure to have // @grant GM_addStyle in the header. My issue was, I also had the default code's // @grant none at the bottom of the header. Removed that piece and now all my css works. Hope this helps someone else if they are stuck on this too.

My 2 cents on the topic, thought it might be interesting to someone, I modified PaarCrafter's answer, to allow multiple lines without brackets:

usage:

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

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

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

Modified version:

function addGlobalStyle(css = '') {
    let target = document.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);
}

I have GreaseMonkey scripts that run in various engines, this covers all varieties:

--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);
    }
}

This excerpt from a script that was written in 2018 that is known to work in GreasMonkey, TamperMonkey, and ViolentMonkey (probably others too). Adapt the above mentioned addGlobalStyle(css) functions and you should be good to go anywhere .

Here is the solution used by https://userstyles.org, for example when you click on the link "Install style as userscript" on a style page like 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);
    }
}

Note: the code will work on Greasemonkey 4 as well as similar addons. I don't use Tampermonkey which is not open source but this answer may help other users finding this question. It will try to use several built-in functions of different addons before using a pure JavaScript solution. You may only need the code from the else block.

The "if" condition checking the head tag length may not be needed if you are sure the page has a head tag and you can add the node to the head like this instead : document.head.appendChild(node);. However I noticed sometimes there is a JavaScript error saying the head is undefined or null depending on the method used, for example on facebook.com while logged out (at least when using // @run-at document-start which is required for a dark theme to avoid flickering). So checking the length can be useful in this case.

If you want to use multiple lines of CSS code, you can create the css variable with backticks like this:

var css = `
CODE HERE
`;

Update: I just saw this solution is also used in another answer but there was no source mentioned. However you may see the console error document.documentElement is null but it can be solved with a MutationObserver workaround: https://github.com/greasemonkey/greasemonkey/issues/2996#issuecomment-906608348.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top