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?
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";
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; }");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With