Search code examples
cssgreasemonkeyuserscriptstampermonkey

Replace line in css file, using Greasemonkey


I am trying to write a Greasemonkey script that replaces one line of a .css file.

The original line from all.css is

#header {
    background: transparent url('img/bg-graph-top.png?v=7e4ce14d05fb') no-repeat 50% -25px;
} 

I'd like to replace it with

#header {
    background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px;
} 

Based on https://stackoverflow.com/a/6854437/9072294 I tried to write my very first userscript like this:

// ==UserScript==
// @name            swap
// @include         http://tex.stackexchange.com/*
// @include         https://tex.stackexchange.com/*
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

var desiredImage    = "https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png";

//--- Straight image swap:
$('img/bg-graph-top.png?v=7e4ce14d05fb').attr ('src', desiredImage);

/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
    Since this image is transparent, clear the old BG image.
    Also constrain the new img to its container. 
*/
$('#header all').css ('background-', 'none')
                .append ('<url>').find ('img/bg-graph-top.png?v=7e4ce14d05fb')  .attr ('src', desiredImage).css ();

However the image is not changing :(


Solution

  • You are trying to change a background image, not an <img> tag, like that other answer.

    For such things, just use CSS overrides.

    Here's what it looks like in a Greasemonkey/Tampermonkey script:

    // ==UserScript==
    // @name        _TeX SE, Swap header background
    // @match       *://tex.stackexchange.com/*
    // @grant       GM_addStyle
    // @run-at      document-start
    // ==/UserScript==
    
    GM_addStyle ( `
        #header {
            background: transparent url('https://upload.wikimedia.org/wikipedia/commons/0/09/Dummy_flag.png') no-repeat 50% -25px !important;
        }
    ` );
    

    Note the !important flag.

    Also, @run-at document-start may complicate things if your script does any DOM manipulation.

    Anyway, for pure CSS changes, like this one, you are better off using the Stylish extension. It's less fuss and performs better