Add parameters to the URL (redirect) via a Greasemonkey/Tampermonkey/Userscript

陌路散爱 提交于 2019-11-26 23:08:25

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       *://*.reddit.com/*
// @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 + "//"
                + window.location.host
                + oldUrlPath + ".compact"
                + window.location.search
                + window.location.hash
                ;
    /*-- replace() puts the good page in the history instead of the
        bad page.
    */
    window.location.replace (newURL);
}

The example script you showed is using a regex to manipulate the window's location:

replace(/^https?:\/\/(www\.)?twitter.com/, 'https://mobile.twitter.com');

Unsurprisingly, this replaces https://www.twitter.com and http://twitter.com etc. with https://mobile.twitter.com.

Your situation is slightly different, because you want to append a string to your url if it matches some regex. Try:

var url = window.location.href;
var redditPattern = /^https:\/\/pay.reddit.com\/.*/;
// Edit: To prevent multiple redirects:
var compactPattern = /\.compact/;
if (redditPattern.test(url)
    && !compactPattern.test(url)) {
    window.location.href = url + '.compact';
}

See: http://jsfiddle.net/RichardTowers/4VjdZ/3 for test case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!