nodiscc nodiscc - 1 year ago 159
Javascript Question

Greasemonkey: add parameters to URL

I'd like to write a Greasemonkey/userscript that automatically adds

to URLs starting with so It automatically redirects me to the mobile version.

I've been looking at similar userscripts, particularly this one: trying to figure out how to edit the replacement pattern, but I lack skills in this domain.

How do I write a greasemonkey script that redirects me from*


Answer Source

The script should do these things:

  1. Detect if the current URL is already to the compact site.
  2. Load the compact version of the page if necessary.
  3. Beware of "anchor" URLS (they end with "fragments" or "hashes" (#...) ) and account for them.
  4. Keep the unwanted pages out of the browser history so that the back button works well. Only .compact URL's will be remembered.
  5. By running at document-start, the script can give better performance in this case.

To that end, this script works:

// ==UserScript==
// @name        _Reddit, ensure compact site is used
// @match       *://**
// @run-at      document-start
// @grant       none
// ==/UserScript==

var oldUrlPath  = window.location.pathname;

/*--- Test that ".compact" is at end of URL, excepting any "hashes"
    or searches.
if ( ! /\.compact$/.test (oldUrlPath) ) {

    var newURL  = window.location.protocol + "//"
                + oldUrlPath + ".compact"
                + window.location.hash
    /*-- replace() puts the good page in the history instead of the
        bad page.
    window.location.replace (newURL);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download