重定向后如何监听浏览器后退/前进按钮并执行指定JS函数?
解决方案
针对你遇到的GET跳转后退无法检测的问题,可以通过以下几种方式实现需求:
方法一:使用SessionStorage标记跳转来源
在PAGE1触发GET跳转前,存入一个标记到sessionStorage;当从PAGE2后退回PAGE1时,检查该标记,确认是后退操作后执行目标函数并清除标记。
// PAGE1:给跳转链接添加点击事件,存入标记 document.querySelector('a[href="PAGE2"]').addEventListener('click', () => { sessionStorage.setItem('fromPage1ToPage2', 'true'); }); // PAGE1:修改后的检测函数 function detectHistoryEvent() { const navEntry = performance.getEntriesByType("navigation")[0]; // 处理原生back_forward场景 if (navEntry.type === 'back_forward') { themethod(); } // 处理GET跳转后退的场景 else if (navEntry.type === 'navigate' && sessionStorage.getItem('fromPage1ToPage2')) { themethod(); sessionStorage.removeItem('fromPage1ToPage2'); // 清除标记,避免后续误触发 } } detectHistoryEvent();
方法二:利用History State与Popstate事件
通过自定义history状态标记跳转行为,监听浏览器的popstate事件来判断是否为后退操作。
// PAGE1:拦截GET跳转,添加自定义history状态 document.querySelector('a[href="PAGE2"]').addEventListener('click', (e) => { e.preventDefault(); // 给当前PAGE1的history条目添加自定义状态 history.pushState({ isFromPage1Jump: true }, '', window.location.href); // 执行跳转 window.location.href = e.target.href; }); // PAGE1:监听popstate事件 window.addEventListener('popstate', (event) => { if (event.state?.isFromPage1Jump) { themethod(); // 重置history状态,避免重复触发 history.replaceState(null, '', window.location.href); } }); // 保留原有的back_forward场景检测 function detectHistoryEvent() { const navEntry = performance.getEntriesByType("navigation")[0]; if (navEntry.type === 'back_forward') { themethod(); } } detectHistoryEvent();
方法三:结合Document Referrer(局限性较大)
如果PAGE2仅能从PAGE1的GET跳转进入,可以通过document.referrer判断来源,结合navigation.type进行检测:
function detectHistoryEvent() { const navEntry = performance.getEntriesByType("navigation")[0]; const isFromPage2 = document.referrer.includes('PAGE2'); if (navEntry.type === 'back_forward' || (navEntry.type === 'navigate' && isFromPage2)) { themethod(); } } detectHistoryEvent();
方案对比
- 方法一兼容性最好,逻辑简单,适合大多数场景;
- 方法二更灵活,能精细控制history行为,但需要拦截默认跳转;
- 方法三局限性高,仅适用于PAGE2来源单一的场景。
内容的提问来源于stack exchange,提问作者Mr. Kenneth
相关产品推荐
相关产品推荐

