Click here to Skip to main content
15,884,675 members
Articles / Web Development / HTML

User Scripts (JS) and User Styles (CSS)

Rate me:
Please Sign up or sign in to vote.
1.63/5 (5 votes)
4 May 2016CPOL6 min read 22.1K   1   4
Run/apply your own JS/CSS on any website

I had printed this article in the Indian magazine Open Source For You in February 2016. I have posted the original version of the article on CodeProject to reach a wider audience.

Introduction

JavaScript and CSS are not just server-end technologies. You can write your own scripts and stylesheets and make your Web browser apply to them to any website. In this article, we will breeze through this esoteric form of JavaScript and CSS, and learn why it has thousands of loyal fans, many of whom have not even written a single line of JavaScript or CSS, but do swear their browsing method is a cut above the rest.

Background

How many times have you wished that some websites did not really make those bad choice of colors or contrast or font sizes? Haven't you wished some others did not make intolerable demands on your patience or try to make you feel vulnerable? Well... user styles and scripts can help. They can make recalcitrant websites behave and good websites become better. Finally, you will be in control.

User Scripts & User Styles

User scripts and user styles are supposed to be written by end-users (we, the ones using the browser) to customize the functionality or the look-and-feel of websites (that we visit).

This is quite contrary to the popular perception that CSS and JavaScript files are authored by web designers and can only be part of the websites they originate from.

While it may seem that a knowledge of CSS and JavaScript is pre-requisite, most fans simply visit websites such as OpenUserJS.org or UserStyles.org to get what they want. Just like bookmarklets, thousands of user JS and user CSS for almost every imaginable purpose have been published. This writer writes almost all of his user scripts/styles. If you are a Web developer, you might want to do the same.

In Firefox/Seamonkey/Iceape browsers, you can use Greasemonkey add-on to manage and execute user scripts and the Stylish add-on to manage and apply user styles. Both add-ons provide a text editor to write your JS/CSS. The add-ons also let you apply the CSS/JS to a specific site (using wildcards in URLs) or to all sites in general.

The Greasemonkey and Stylish add-ons for Firefox makes it easy to manage and apply user scripts and styles.

The pre-Blink Opera (12.x and older) browser always had built-in support for user scripts and styles. It had to do that, as it was usually eliminated from popular websites because of ill-informed web programmers who relied on browser detection (which favoured Internet Explorer) instead of feature detection. Opera has now become a Chrome clone and the Presto-engine-based Opera 12.x has become obsolete.

The utility of user scripts and user styles are best illustrated by examples.

User Script Examples

Here is the well-known Gmail login page. There was a time when webmail providers would leave the "Stay signed in" unchecked by default. Now, it is checked by default (not just by Google but by other providers too). Unchecking this box every time you want to log in is an extra step that is easy to forget.

The "Stay signed-in" check box in many big websites are are selected by default. This means that these websites will continue to track you even when you click the log out link and when you are on any of their "partner" websites. A partner website is pretty much any any website these days - anything that has their ads or social networking plugins or webmaster tools/tracker JavaScript.

How do you get it automatically unchecked? This Greasemonkey script can do it for you.

JavaScript
// ==UserScript==
// @name        Uncheck Google Signed-In Checkbox
// @description Automatically unchecks the "Stay signed-in" check box
// @include     https://accounts.google.com/*
// @version     1
// @grant       none
// ==/UserScript==

document.addEventListener("DOMContentLoaded",
                          uncheckGoogleStaySignedInButton,
                          false);

function uncheckGoogleStaySignedInButton() {
  try {
    document.getElementById("PersistentCookie").checked = false;
  } catch (err) {
    console.error("UGSIC Greasemonkey Error: " + err);
  }  
}

The Greasemonkey add-on executes this script on all pages matching the @include filter. The script finds the checkbox and unchecks it. (With minor changes, you can make the same script work on the Yahoo Mail login page too.)

Before writing the script, you have to find the HTML element ID of the checkbox. As any Web developer worth his/her salt knows, this can be accomplished by right-clicking the checkbox on the web page and selecting "Inspect element" from the context menu.

This screenshot show the text editor of the Greasemonkey add-on with the code to uncheck the "Stay signed-in" check box.

Do you find the pre-roll Yahoo Mail page asking you for your phone number annoying? Then, this user script will automatically get you past the page.

JavaScript
// ==UserScript==
// @name        Bypass Phone Number Prompt on Yahoo Mail
// @description Get past the page that asks for your phone number
// @include     https://edit.yahoo.com/progreg/*
// @exclude     %exclude%
// @version     1
// @grant       none
// ==/UserScript==

document.addEventListener("DOMContentLoaded", 
                          getPastPhoneNumberPage, 
                          false);

function getPastPhoneNumberPage() {
  try {
      //window.alert("Moving past the page");
      location.href = "https://mail.yahoo.com";
  } catch (err) {
    console.log("BPNPYM Greasemonkey Error: " + err);
  }  
}   

If you refused to provide your number once, then should not the site respect and remember your decision? By playing dumb every time you log in, it is trying to coerce you into parting with your number.

User Style Examples

Here is a DuckDuckGo page. I use this search engine as the default because it has better respect for people. However, I found that the colors and the contrast on its web pages were not much to my liking. So, I wrote a User CSS for it, remembering to suffix the styles with a "!important" attribute to override the pages authors' setting.

These screenshots show the "before" and "after" appearances of a DuckDuckGo search engine results page. The actual stylesheet code is not so much important as the scope and possibility that these screenshots illustrate.

For the Wikipedia website, I use this CSS because the pages are usually text-heavy and take up the entire width of the screen. On big monitors, they can literally be a pain in the neck.

JavaScript
* { font-family: Century Schoolbook L!important; }
div#content { font-size: 1.2em; width: 7in;  }

The menu of the Stylish add-on will allow you to install not only your stylesheets but also those published by others on the userstyles.org website.

User JS/CSS on the Mobile

Being a fan of user scripts and styles, I added the ability to run them in a namesake browser that I created for Android. While the user styles can be written in the usual way, the user scripts have to be written in bookmarklet[1] format - prefixed with "javascript:". For example, to edit a web page, I use this script.

JavaScript
javascript:(function() { document.body.contentEditable=true;document.designMode='on'; }) ();  

This script will work even in a desktop browser, such as Internet Explorer or Firefox, but perhaps not Chrome. Go ahead and try it.

Subhash Browser & Feed Reader, an app created by me, supports user scripts and styles. JS and CSS files prefixed with an underscore will be executed/applied automatically on all pages.

Maintenance

Of course, web pages change and the IDs (or whatever you had tried to meddle with) changes along with them. Your Greasemonkey script may eventually stop working. You will have to either fix it yourself or update it from the Web or find a new one.

Last year, I published a Greasemonkey script that would go through all posts in a Facebook profile's Activity Log and delete one post after another - it is much fun that way rather than asking Facebook to delete it all in one go. This was necessitated because an older Greasemonkey script referred by an equally old article[2] had become obsolete. In another case, a Greasemonkey script I wrote to download YouTube videos as MP4/FLV/WebM files stopped working within a month of release. Although I fixed it up, it may not be long before the script needs attention again.

This screenshot shows two of my User JS in action. One has displayed a button to download a YouTube video. The video in turn shows a User JS in Opera 12.x browser deleting my Facebook posts!

Points of Interest

While it seems that user scripts and styles have a finite shelf life, the beauty of open source ensures that anyone can revive a JS or CSS and bring it back to the community.

Apart from the above-mentioned sites, greasyfork.org also provides user scripts. For a long time, Greasemonkey developers had the UserScripts.org site to distribute user scripts. Before becoming defunct[3], the site was troubled by DMCA requests from control-freak webmasters who did not quite understand user scripts, buckled under spam/DDOS attacks and went without a full-time admin. Many of the original developers from userscripts.org have not yet moved to the new sites. Hence, many user scripts are littered all over the web including sites such as gist.github.com. I would suggest ordinary readers to first trawl the comments section or the forums before installing any script or style. The Greasemonkey and Stylish extensions can be easily installed by doing a search in the Firefox add-on manager.


References

  1. Bookmarklet Builder - http://subsimple.com/bookmarklets/jsbuilder.htm
  2. Jennifer Golbeck: I Decided to Delete All My Facebook Activity - http://www.slate.com/articles/technology/future_tense/2014/01/facebook_cleansing_how_to_delete_all_of_your_account_activity.html
  3. Hacker News: Passing the torch on userscripts.org - https://news.ycombinator.com/item?id=1574840

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer www.VSubhash.in
India India
V. Subhash is an invisible Indian writer, programmer and illustrator. In 2020, he wrote one of the biggest jokebooks of all time and then ended up with over two dozen mostly non-fiction books including Linux Command-Line Tips & Tricks (first paperback to have syntax highlighting in colour), CommonMark Ready Reference (the first book on CommonMark), PC Hardware Explained, Cool Electronic Projects and How To Install Solar. His book Quick Start Guide to FFmpeg was published by Apress/SpringerNature in 2023. He wrote, illustrated, designed and produced all of his books using only open-source software. Subhash has programmed in more than a dozen languages (as varied as assembly, Java and Javascript); published software for desktop (NetCheck), mobile (Subhash Browser & RSS Reader) and web (TweetsToRSS); and designed several websites. As of 2024, he is working on a portable Javascript-free CMS using plain-jane PHP and SQLite. Subhash also occasionally writes for Open Source For You magazine and CodeProject.com.

Comments and Discussions

 
QuestionWho is the Troll? Pin
Richard MacCutchan7-Jul-17 5:59
mveRichard MacCutchan7-Jul-17 5:59 
GeneralMy vote of 5 Pin
INDtanay16-Feb-17 1:34
INDtanay16-Feb-17 1:34 
QuestionPlease do not report this article Pin
Sean Ewington4-May-16 3:37
staffSean Ewington4-May-16 3:37 
PraiseIts a nice article Pin
Member 124957731-May-16 0:26
Member 124957731-May-16 0:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.