Skip to content

Instantly share code, notes, and snippets.

@shibeta
Created June 30, 2025 12:33
Show Gist options
  • Save shibeta/9892027ad5e253b4d44776b3440e6e92 to your computer and use it in GitHub Desktop.
Save shibeta/9892027ad5e253b4d44776b3440e6e92 to your computer and use it in GitHub Desktop.
Tampermonkey脚本,尝试向reddit页面中自动添加tl=zh-hans以启用reddit自带的翻译功能
// ==UserScript==
// @name Reddit 自动中文翻译
// @namespace shibeta
// @version 2.0
// @description 自动将 Reddit 页面的 'tl' URL 参数设置为 'zh-hans' 以触发翻译。使用 sessionStorage 防止在不支持翻译的页面上发生无限重定向循环。
// @author shibeta
// @match http://*.reddit.com/*
// @match https://*.reddit.com/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
const currentUrl = new URL(window.location.href);
const params = currentUrl.searchParams;
const currentTl = params.get('tl');
// 1. 如果页面已经成功翻译,则什么都不做
if (currentTl === 'zh-hans') {
// console.log("页面已翻译,脚本退出。");
return;
}
// 构造一个不含 'tl' 参数的“干净”URL作为 sessionStorage 的键
// 这确保了我们比较的是重定向前后的同一个基础页面
const cleanUrl = new URL(window.location.href);
cleanUrl.searchParams.delete('tl');
const storageKey = 'redirect_attempted_for_' + cleanUrl.toString();
// 2. 检查 sessionStorage 中是否已经有尝试过的记录
if (sessionStorage.getItem(storageKey)) {
// console.log("已尝试过为此 URL 添加翻译参数但可能失败了,为避免循环,脚本已停止。");
return;
}
// 3. 如果既未翻译也未尝试过,则执行重定向
// a. 先在 sessionStorage 中记录下“即将尝试”的状态
// console.log(`正在为 ${storageKey} 设置尝试标记,并准备重定向。`);
sessionStorage.setItem(storageKey, 'true');
// b. 添加 'tl' 参数并重定向
params.set('tl', 'zh-hans');
currentUrl.search = params.toString();
window.location.replace(currentUrl.toString());
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment