GM_addStyle equivalent in TamperMonkey

arserbin3 picture arserbin3 · May 15, 2014 · Viewed 38.4k times · Source

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?

Answer

A-312 picture A-312 · Oct 16, 2015

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