Search code examples
javascriptgreasemonkey

Change a background image with Greasemonkey?


I would like to change the background of the website. The problem is that I have almost zero experience on Greasemonkey. I have this script:

// ==UserScript==
// @name        Tamo
// @namespace   TamoImageChanger
// @include     https://sistema.tamo.lt*
// @version     1
// @grant       none
// ==/UserScript==
var images = document.getElementsByTagName("img");
var x = 0;
while (x < images.length) {
    if (images[x].src == "https://sistema.tamo.lt/Content/img/new/login_background2.jpg") {
        images[x].src = "the image i want to be displayed";
    }
    x = x + 1;
}

but it works only when I am in this webpage:
      https://sistema.tamo.lt/Content/img/new/login_background2.jpg

I want the script to change the background in this webpage though:
      https://sistema.tamo.lt/Prisijungimas/Login


Solution

  • The website you're trying to visit is displaying this image as a background image and not a image tag.

    And this script actually change the source of all <img/> tags.

    var images = document.getElementsByTagName("img");
    

    So I did customize your script to accomplish whatever you want to do. To make this more educative, I gonna explain step by step what happen.

    // Here I'm retrieving the tag displaying the picture by specifying exact path.
    var image = document.querySelector("body > .container_2 > .col_left");
    
    // Here I just change the background image by yours.
    image.style.backgroundImage = "url('INSERT YOUR IMAGE')";
    

    -

    EDIT

    As Brock Adams mentionned below, you can also accomplish the same work as above, GreaseMonkey style.

    GM_addStyle("div[style*='login_background2.jpg'] {background-image: url('INSERT YOUR IMAGE')!important;} ")