Greasy Fork

Greasy Fork is available in English.

Reddit Default Sort

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

当前为 2025-02-11 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Reddit Default Sort
// @version      1.1.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 http://greasyfork.icu/users/1315976
// ==/UserScript==

(function() {
    'use strict';

    // Default values
    const defaultHomePageSort = "new";
    const defaultSubredditSort = "new";
    // This allows you to use the Reddit filters temporariliy, without it redirecting you to the default
    let lastUrl = "";

    // 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 && !homeUrls.includes(lastUrl)) {
            window.location.replace(homeTargetUrl);
            return;
        }

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

        if (subredditPattern.test(currentUrl)) {
            const match = currentUrl.match(subredditPattern);
            const subredditName = match[1];

            // Check if were still on the same sub indicates the user only changed their sort we should not set it back
            if (subredditPattern.test(lastUrl)) {
              const matchLast = lastUrl.match(subredditPattern);
              if (subredditName == matchLast[1]) {
                return;
              }
            }

            const targetUrl = `https://www.reddit.com/r/${subredditName}/${subredditSort}`;
            const altTargetUrl = `https://www.reddit.com/r/${subredditName}/${subredditSort}/`;

            if (currentUrl !== targetUrl && currentUrl !== altTargetUrl) {
                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) {
        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);

})();