// ==UserScript== // @name LinuxDO URL 更改优化 // @namespace Neuroplexus_Do_State-Manager // @version 1.1 // @description 优化 linux.do 论坛的历史记录管理, 当 URL 更改时, 不进行不必要的历史记录堆栈增加. // @author Neuroplexus // @match https://linux.do/t/topic/* // @grant none // ==/UserScript== (function() { 'use strict'; // 保存原始的历史方法 const originalPushState = window.history.pushState; const originalReplaceState = window.history.replaceState; // 用于存储状态的数组 let stateStack = []; let currentStateIndex = -1; // 获取当前 topic ID function getTopicId(url) { const match = url.match(/\/t\/topic\/(\d+)/); return match ? match[1] : null; } // 添加状态到栈中 function addToStateStack(state, title, url) { // 如果不是在栈顶,删除当前位置之后的所有状态 if (currentStateIndex < stateStack.length - 1) { stateStack = stateStack.slice(0, currentStateIndex + 1); } stateStack.push({ state: state, title: title, url: url }); currentStateIndex++; } // 重写 pushState 方法 window.history.pushState = function(state, title, url) { const currentTopicId = getTopicId(window.location.href); const newTopicId = getTopicId(url); // 如果在同一个 topic 内导航,使用增强的 replaceState if (currentTopicId && newTopicId && currentTopicId === newTopicId) { addToStateStack(state, title, url); return originalReplaceState.call(this, state, title, url); } // 其他情况使用原始的 pushState addToStateStack(state, title, url); return originalPushState.call(this, state, title, url); }; // 重写 replaceState 方法 window.history.replaceState = function(state, title, url) { if (currentStateIndex >= 0) { stateStack[currentStateIndex] = { state: state, title: title, url: url }; } return originalReplaceState.call(this, state, title, url); }; // 监听 popstate 事件(前进/后退按钮触发) window.addEventListener('popstate', function(event) { // 查找目标状态在栈中的位置 const targetUrl = window.location.href; const targetIndex = stateStack.findIndex(item => item.url === targetUrl); if (targetIndex !== -1) { currentStateIndex = targetIndex; // 不需要手动调用 replaceState,因为浏览器已经更新了 URL } }); // 初始化当前页面状态 addToStateStack(history.state, document.title, window.location.href); })();