Xeo Xeo - 1 month ago 11
CSS Question

How to change a class CSS with a Greasemonkey script?

I'm trying to set the background image of the body, but only where it uses the class

banner_url
. The HTML is as follows:

<body id="app_body" class="banner_url desktopapp" data-backdrop-limit="1">


Basically, I would like to force the page to use the following CSS instead:

.banner_url {
background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}


I am trying to do this using Greasemonkey if it makes any difference. Does anyone know how I can go about this? I started with the following, however haven't had much luck:

function randomBG(){
document.getElementsByClassName("banner_url").style.backgroundImage="url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg')no-repeat center center fixed;";
}
randomBG();

Answer

For this, just use the CSS cascade. Add a style sheet to the page with GM_addStyle(). Note that we use the !important flag to cover certain potential conflicts.

A complete script:

// ==UserScript==
// @name     _Override banner_url styles
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_addStyle
// ==/UserScript==

GM_addStyle ( "                                     \
    .banner_url {                                   \
        background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed !important; \
        -webkit-background-size: cover !important;  \
        -moz-background-size: cover !important;     \
        -o-background-size: cover !important;       \
        background-size: cover !important;          \
    }                                               \
" );

Also, for pure CSS manipulation, the Stylish add-on is a better choice than Greasemonkey.