The beginner's guide to Greasemonkey scripting
How to make the web work exactly as you want it to
Part 2 - Set CSS styles
This script won't, however, work with frames; it'll only change the main body background style. If your eye-bleedingly backgrounded page has frames, your best bet to hit all of them is to insert a CSS style that overrides the existing one.
To edit the existing file, right-click the monkey face and choose 'Manage User Scripts'. Select your script and click Edit to bring it up again in your chosen text editor. While you're testing, you don't need to close the editor or the Manage User Scripts dialog – just save the file and try reloading the page.
function addCss(cssString) {
var head = document.
getElementsByTagName('head')[0];
return unless head; var newCss = document.createElement('style');
newCss.type = "text/css";
newCss.innerHTML = cssString;
head.appendChild(newCss);
}
addCss (
'* { background-color: #ffffff ! important; }'
);
The first function (addCss) sets up a way of adding a global CSS file to the page. As before, document refers to the current page, but in this instance we're using the getElementsByTagName function (which does what it says on the tin) to get the first head element.
For those of you who aren't entirely familiar with CSS: you set your CSS up in the head section of an HTML file, so we need to get that element to act as a parent to our new CSS element.
There's an error catching line in there (return without doing anything if there's no head section), then the script creates a style element and gives it the text/css type. The line
Get the best Black Friday deals direct to your inbox, plus news, reviews, and more.
Sign up to be the first to know about unmissable Black Friday deals on top tech, plus get all your favorite TechRadar content.
newCss.innerHTML = cssString
is where the function takes whatever is passed into it, and pastes that into the style element. Then the fully created style element gets added to the head element and we're done.
The final couple of lines are the bit that actually call the function, with the argument that sets the background colour – this goes where cssString is. Note: those are regular brackets (), because you're calling a function, not setting one up.
The ! important flag ensures that your CSS styles override those of the page itself. Effectively, what this does is to add these lines to the header of your HTML page:
background-color: #ffffff ! important;
You can use this technique to set your own CSS preferences for anything else – just make that CSS string, when you call the addCss function, say what you want, eg:
addCss (
'* { background-color: #ffffff ! important;
text-align: center ! important;
color: black ! important; }'
);
to make the background white, and all the text centred and in black.
Current page: Set CSS styles
Prev Page Writing your first Greasemonkey script Next Page Alter specific elements