arserbin3 arserbin3 - 4 months ago 25
CSS Question

GM_addStyle equivalent in TamperMonkey

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?

lpd lpd
Answer

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.

Comments