Reputation: 180
I'd like to write a Greasemonkey/userscript that automatically adds .compact
to URLs starting with https://pay.reddit.com/ so It automatically redirects me to the mobile version.
I've been looking at similar userscripts, particularly this one: https://userscripts.org/scripts/review/112568 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 https://pay.reddit.com/*
to https://pay.reddit.com/*.compact
?
Thanks
Upvotes: 8
Views: 14651
Reputation: 93473
The script should do these things:
#...
) ) and account for them..compact
URL's will be remembered.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);
}
Upvotes: 13
Reputation: 4762
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.
Upvotes: 0