Reddit Default Sort

Automatically sets Reddit's default sorting order for home and subreddits.

As of 2025-02-10. See the latest version.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Reddit Default Sort
// @version      1.0.0
// @description  Automatically sets Reddit's default sorting order for home and subreddits.
// @author       yodaluca23
// @license      MIT
// @match        *://*.reddit.com/*
// @grant        GM_getValue
// @grant        GM_setValue
// @namespace https://greatest.deepsurf.us/users/1315976
// ==/UserScript==

(function() {
    'use strict';

    // Default values
    const defaultHomePageSort = "new";
    const defaultSubredditSort = "new";

    // Function to get the stored sort option, or the default if none is stored.
    function getSortOption(key, defaultValue) {
        let value = GM_getValue(key);
        return value === undefined ? defaultValue : value;
    }

    // Get the stored sort options
    let homePageSort = getSortOption("homePageSort", defaultHomePageSort);
    let subredditSort = getSortOption("subredditSort", defaultSubredditSort);

    // Function to redirect if necessary
    function redirectIfNeeded() {
        const currentUrl = window.location.href;

        // Check for home page URLs
        const homeUrls = [
            "https://www.reddit.com/",
            "https://www.reddit.com/?feed=home",
            "https://www.reddit.com/best/?feed=home",
            "https://www.reddit.com/hot/?feed=home",
            "https://www.reddit.com/top/?feed=home",
            "https://www.reddit.com/new/?feed=home",
            "https://www.reddit.com/rising/?feed=home"
        ];

        const homeTargetUrl = `https://www.reddit.com/${homePageSort}/?feed=home`;

        if (homeUrls.includes(currentUrl) && currentUrl !== homeTargetUrl) {
            window.location.replace(homeTargetUrl);
            return;
        }

        // Check for subreddit URLs
        const subredditPattern = /https:\/\/www\.reddit\.com\/r\/([^/]+)(\/)?(\?.*)?$/;

        if (subredditPattern.test(currentUrl)) {
            const match = currentUrl.match(subredditPattern);
            const subredditName = match[1];
            const targetUrl = `https://www.reddit.com/r/${subredditName}/${subredditSort}`;

            if (currentUrl !== targetUrl) {
                window.location.replace(targetUrl);
            }
        }
    }

    // Function to create the settings UI
    function createSettingsUI() {
        // Create the settings container
        const settingsContainer = document.createElement('div');
        settingsContainer.style.position = 'fixed';
        settingsContainer.style.top = '50%';
        settingsContainer.style.left = '50%';
        settingsContainer.style.transform = 'translate(-50%, -50%)';
        settingsContainer.style.backgroundColor = 'white';
        settingsContainer.style.border = '1px solid #ccc';
        settingsContainer.style.padding = '15px';
        settingsContainer.style.borderRadius = '10px';
        settingsContainer.style.boxShadow = '0px 4px 10px rgba(0, 0, 0, 0.2)';
        settingsContainer.style.zIndex = '1000';
        settingsContainer.style.minWidth = '250px';
        settingsContainer.style.textAlign = 'center';

        // Home page sort select
        const homePageLabel = document.createElement('label');
        homePageLabel.textContent = 'Home Page Sort:';
        const homePageSelect = document.createElement('select');
        homePageSelect.id = 'homePageSortSelect';
        ['best', 'hot', 'top', 'new', 'rising'].forEach(option => {
            const opt = document.createElement('option');
            opt.value = option;
            opt.textContent = option.charAt(0).toUpperCase() + option.slice(1);
            homePageSelect.appendChild(opt);
        });
        homePageSelect.value = homePageSort;

        // Subreddit sort select
        const subredditLabel = document.createElement('label');
        subredditLabel.textContent = 'Subreddit Sort:';
        const subredditSelect = document.createElement('select');
        subredditSelect.id = 'subredditSortSelect';
        ['best', 'hot', 'top', 'new', 'rising'].forEach(option => {
            const opt = document.createElement('option');
            opt.value = option;
            opt.textContent = option.charAt(0).toUpperCase() + option.slice(1);
            subredditSelect.appendChild(opt);
        });
        subredditSelect.value = subredditSort;

        // Save button
        const saveButton = document.createElement('button');
        saveButton.textContent = 'Save Settings';
        saveButton.addEventListener('click', () => {
            homePageSort = document.getElementById('homePageSortSelect').value;
            subredditSort = document.getElementById('subredditSortSelect').value;

            GM_setValue("homePageSort", homePageSort);
            GM_setValue("subredditSort", subredditSort);

            alert('Settings Saved!');
            settingsContainer.remove(); // Remove the settings UI after saving
            redirectIfNeeded(); // Redirect immediately after saving
        });

        // Close button
        const closeButton = document.createElement('button');
        closeButton.textContent = 'Close';
        closeButton.addEventListener('click', () => {
            settingsContainer.remove();
        });

        // Append elements
        settingsContainer.appendChild(homePageLabel);
        settingsContainer.appendChild(homePageSelect);
        settingsContainer.appendChild(subredditLabel);
        settingsContainer.appendChild(subredditSelect);
        settingsContainer.appendChild(saveButton);
        settingsContainer.appendChild(closeButton);

        document.body.appendChild(settingsContainer);
    }

    // Add a button to the page to open the settings
    function addSettingsButton() {
        const container = document.querySelector('.pl-lg.gap-xs.flex.items-center.justify-end');

        if (!container) {
            console.warn("Sort Settings button: Target container not found.");
            return; // Exit if container is missing
        }

        const settingsButton = document.createElement('button');
        settingsButton.textContent = 'Sort Settings';
        settingsButton.style.marginLeft = '10px'; // Add spacing
        settingsButton.className = 'btn btn-primary'; // Reddit-style button class
        settingsButton.addEventListener('click', createSettingsUI);

        container.appendChild(settingsButton);
    }


    // Initialize
    addSettingsButton();
    redirectIfNeeded();

      // Function to monitor URL changes in single-page app
    function observeUrlChanges(callback) {
        let lastUrl = location.href;

        new MutationObserver(() => {
            if (location.href !== lastUrl) {
                lastUrl = location.href;
                callback();
            }
        }).observe(document, { subtree: true, childList: true });

        // Also intercept history changes
        const pushState = history.pushState;
        const replaceState = history.replaceState;

        history.pushState = function() {
            pushState.apply(this, arguments);
            callback();
        };
        history.replaceState = function() {
            replaceState.apply(this, arguments);
            callback();
        };
    }

    // Run `redirectIfNeeded` whenever Reddit changes the page
    observeUrlChanges(redirectIfNeeded);

})();