Chrome+Tampermonkey脚本自动跳转后后退按钮失效问题求助
问题原因
这是Chromium浏览器的**历史记录合并(history coalescing)**特性导致的:当页面通过无用户交互的脚本自动跳转时,浏览器会将跳转前后的页面合并为一条历史记录,导致后退按钮无法回到上一页;只有页面存在真实用户交互后,跳转才会生成独立的历史条目。
解决方案
可以通过history.pushState手动管理历史栈,并配合popstate事件处理后退操作,让浏览器保留每一次跳转的历史记录,同时避免后退后再次自动跳转。
修改后的脚本代码
// ==UserScript== // @name demo // @description demo // @version 1.1 // @match https://www.ebay.com/sch/* // ==/UserScript== let search_url = 'https://www.ebay.com/sch/i.html?_nkw='; let search_arr = ['iphone','android','laptop']; // 获取当前页面对应的搜索词索引 let currentKeyword = new URLSearchParams(window.location.search).get('_nkw'); let index = currentKeyword ? search_arr.indexOf(currentKeyword) : (+localStorage.index || 0); // 如果当前关键词不在数组中,回退到localStorage记录的索引 if (index === -1) { index = +localStorage.index || 0; } const delay = 15000; let autoJumpTimer = null; // 监听后退事件,清除自动跳转定时器并恢复索引 window.addEventListener('popstate', (e) => { if (e.state?.index !== undefined) { index = e.state.index; localStorage.index = index; } if (autoJumpTimer) { clearTimeout(autoJumpTimer); autoJumpTimer = null; } }); // 触发自动跳转 autoJumpTimer = setTimeout(() => { const nextIndex = (index < search_arr.length - 1) ? index + 1 : 0; localStorage.index = nextIndex; // 将当前页面状态推入历史栈,确保后退能回到当前页 history.pushState({ index: index }, document.title, window.location.href); // 执行跳转 location.href = search_url + search_arr[nextIndex]; }, delay);
关键修改说明
- 页面加载时优先从当前URL提取搜索词匹配索引,避免刷新页面导致索引错误
- 用
history.pushState在跳转前将当前页面状态存入历史栈,强制浏览器保留该页面的历史记录 - 监听
popstate事件,用户点击后退时清除自动跳转定时器并恢复对应索引,避免后退后再次自动跳转 - 将索引更新逻辑移到跳转前,确保localStorage记录的是下一个要跳转的索引
内容的提问来源于stack exchange,提问作者Jamesfo
相关产品推荐
相关产品推荐

