GM_addStyle equivalent in TamperMonkey
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');
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; }');
"