Greasy Fork

Greasy Fork is available in English.

自动跳转到 Reddit 官方中文翻译的页面

Automatically jump to the official Chinese translation page of Reddit

< 脚本 自动跳转到 Reddit 官方中文翻译的页面 的反馈

评价:一般 - 脚本能用,但还有一些问题

§
发布于:2025-06-27

实用的功能,但有些reddit没有官方中文翻译,这个脚本会导致死循环,以下是修复的代码

// ==UserScript==
// @name         自动跳转到 Reddit 官方中文翻译的页面 (防循环最终修复版 v3)
// @namespace    reddit.com
// @version      1.1
// @description  Automatically jump to the official Chinese translation page of Reddit, with robust loop protection.
// @author       xxnuo & AI-assisted fix
// @match        *://*.reddit.com/*
// @grant        none
// @run-at       document-start
// @license      MIT
// @downloadURL https://update.greasyfork.icu/scripts/537173/%E8%87%AA%E5%8A%A8%E8%B7%B3%E8%BD%AC%E5%88%B0%20Reddit%20%E5%AE%98%E6%96%B9%E4%B8%AD%E6%96%87%E7%BF%BB%E8%AF%91%E7%9A%84%E9%A1%B5%E9%9D%A2.user.js
// @updateURL https://update.greasyfork.icu/scripts/537173/%E8%87%AA%E5%8A%A8%E8%B7%B3%E8%BD%AC%E5%88%B0%20Reddit%20%E5%AE%98%E6%96%B9%E4%B8%AD%E6%96%87%E7%BF%BB%E8%AF%91%E7%9A%84%E9%A1%B5%E9%9D%A2.meta.js
// ==/UserScript==

(function() {
    'use strict';

    const REDIRECT_ATTEMPT_KEY = 'reddit_zh_redirect_attempted_pathname';
    const redditPostPattern = /^(https?:\/\/)?([a-zA-Z0-9-]+\.)?reddit\.com\/r\/[a-zA-Z0-9_]+\/comments\/[a-zA-Z0-9_]+(\/[a-zA-Z0-9_]*\/?)?($|\?.*)/;

    // --- 新增代码:用于锁定当前页面的布尔标志 ---
    // 这个标志在单次页面加载期间保持不变,防止 MutationObserver 重新触发跳转。
    let loopDetectedThisLoad = false;

    let redirectCheckTimer = null;

    function performRedirectChecks() {
        // --- 新增代码:检查页面是否已被锁定 ---
        if (loopDetectedThisLoad) {
            return;
        }

        const currentUrlObj = new URL(window.location.href);
        const currentPathname = currentUrlObj.pathname;

        const attemptedPathname = sessionStorage.getItem(REDIRECT_ATTEMPT_KEY);
        if (attemptedPathname && attemptedPathname === currentPathname) {
            // --- 核心修改:检测到循环后,设置标志位并中止,但不再清除 sessionStorage ---
            // sessionStorage 的标记需要保留,以便下次完整页面加载时(如手动刷新)还能检测到。
            loopDetectedThisLoad = true;
            console.log(`[Reddit Translate] Loop detected for path: ${currentPathname}. Locking redirects for this page load.`);
            return;
        }

        // 如果是导航到一个新页面,旧的标记就不相关了,可以安全地清除
        // (实际上,在下面的 setItem 时它会被覆盖,但显式清除更清晰)
        sessionStorage.removeItem(REDIRECT_ATTEMPT_KEY);

        if (!redditPostPattern.test(window.location.href)) {
            return;
        }

        if (currentUrlObj.searchParams.get('tl') !== 'zh-hans') {
            sessionStorage.setItem(REDIRECT_ATTEMPT_KEY, currentPathname);
            console.log(`[Reddit Translate] Attempting to translate path: ${currentPathname}`);

            currentUrlObj.searchParams.set('tl', 'zh-hans');
            window.location.replace(currentUrlObj.href);
            return;
        }
    }

    function scheduleRedirectCheck() {
        clearTimeout(redirectCheckTimer);
        redirectCheckTimer = setTimeout(performRedirectChecks, 100);
    }

    performRedirectChecks();

    const observer = new MutationObserver(scheduleRedirectCheck);
    const setupObserver = () => {
        const targetNode = document.head || document.documentElement;
        if (targetNode) {
            observer.observe(targetNode, {
                childList: true,
                subtree: true
            });
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', setupObserver);
    } else {
        setupObserver();
    }
})();

发布留言

登录以发布留言。