user1534513
user1534513

Reputation: 1

Writing a userscript that replaces a background image

This is the code

// ==UserScript==
// @name           Wood Background
// @namespace      http://www.nationstates.net/nation=ellorn
// @description    Changes background to wood finish
// @include       http:*//w11.zetaboards.com/Allied_Republics/*
// ==/UserScript==


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: #00ff00                          url('http://awesomewallpapers.files.wordpress.com/2010/01 /wooden_top.jpg') no-repeat 

fixed center;  }'
);

I'm trying to replace the background of the site: http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg

Upvotes: 0

Views: 1233

Answers (2)

Christoph
Christoph

Reputation: 51211

You can define your own user-stylesheet to overwrite the author stylesheets of websites. I think this would be better suited to alter CSS than writing javascript.

Here is a short introduction on how to achieve that.

Besides from that your code should work in general if you hand over the CSS-string correctly (fixed quoting and linebreak):

var css = "* { background: #00ff00 url('http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg') no-repeat fixed center;  }";

addCss ( css );

Note however, that * will break, since you are applying the wooden background to every element, not only your background-element (HTML or body or a wrapper div).

Upvotes: 0

Brock Adams
Brock Adams

Reputation: 93473

For just style changes, use the Stylish add-on (some variant of this is available on almost every browser).

Stylish is faster, lighter, and easier than Greasemonkey or userscripts. There are plenty of pre-made styles available at userstyles.org.

Barring that, use built-in functions, like GM_addStyle().

The following script works on Firefox and Chrome, and probably a few other browsers. (There was a syntax error in the CSS string) :

// ==UserScript==
// @name        Wood Background
// @namespace   http://www.nationstates.net/nation=ellorn
// @description Changes background to wood finish
// @include     http:*//w11.zetaboards.com/Allied_Republics/*
// ==/UserScript==

GM_addStyle (
    "* { background: #00ff00 "
    + "url('http://awesomewallpapers.files.wordpress.com/2010/01/wooden_top.jpg')"
    + " no-repeat fixed center; }"
);

Note that it would be best to replace the * with body.

Upvotes: 2

Related Questions