Reddit Redirector

A simple script that automatically redirects Reddit links to a more privacy-focused alternative. libreddit.freedit.eu

< 腳本Reddit Redirector的回應

提問/評論

NotYou管理員
§
發表於:2023-04-20
編輯:2023-04-20

You could make your code shorter, here is a shorter solution:

// ==UserScript==
// @name         Reddit Redirector
// @namespace    https://gf.qytechs.cn/
// @version      1.0
// @description  A simple script that automatically redirects Reddit links to a more privacy-focused alternative.
// @author       Takomine
// @license      MIT
// @icon         https://www.iconpacks.net/icons/2/free-reddit-logo-icon-2436-thumb.png
// @match        *://*.reddit.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Redirect Reddit links to Teddit
    function redirectRedditToTeddit() {
        var currentHost = window.location.hostname;

        // If current host is "old.reddit.com", or "www.reddit.com", or "reddit.com", then redirect.
        if (currentHost.match(/^(old|www|)\.?reddit\.com$/)) {
            var newURL = location.protocol + '//libreddit.freedit.eu' + location.pathname + location.search;

            if (location.replace) {
                location.replace(newURL);
            } else {
                window.location.href = newURL;
            }
        }
    }

    // Call the redirect function
    redirectRedditToTeddit();

})();
takomine作者
§
發表於:2023-04-21

I just tested it and it works well with minimal code wow. I don't have any knowledge in making userscripts. I just googled some basic queries and based my code from various examples. This is a learning example. Thanks.

NotYou管理員
§
發表於:2023-04-21
編輯:2023-04-21

I could explain it to you.

First of all, I changed match to this:

// @match *://*.reddit.com/*

We are going to check hostname and subdomain later anyway, so we don't need big @match structures.

Then I changed window.location.href to window.location.hostname because we only need test check hostname (bold URL part here: httpsㅤ://reddit.com/r/ProgrammerHumor).

Then using regular expression I was checking if current hostname is hostname we need.

There is little explanation to line 21:

We are checking if the line starts and ends with old.reddit.com, or www.reddit.com, or reddit.com. (Also, it can match .reddit.com, but I that's not a problem because that's invalid URL, so browser won't load it)

I also check if location.replace method exists, if it exists, then I'm using it. It works better in some of the cases, than location.href. But if it doesn't exist in the current version of the browser, then I just use location.href because we have no other choice.

發表回覆

登入以回復

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址