解决浏览器回退后订单页Continue按钮失效问题
解决方案
问题出在浏览器的往返缓存(BF Cache):当用户从预订页回退时,订单页是从缓存中恢复的而非重新加载,这会导致原有的事件监听器失效,且旧的window.performance.navigation API已被现代浏览器废弃,无法准确检测回退场景。
以下是可行的脚本,核心是利用pageshow事件(页面加载/从缓存恢复时都会触发)重新绑定按钮事件:
<script type="text/javascript"> function handleContinueButtonClick() { localStorage.setItem("continueClicked", true); window.location.href = 'https://www.website.com/go-to-booking'; } // 封装绑定按钮事件的函数 function bindContinueButton() { const continueButton = document.querySelector('.shlGd4v [data-hook="FormDetailsButtons.continue"]'); if (continueButton) { // 先移除已有监听(避免重复绑定),再添加新监听 continueButton.removeEventListener("click", handleContinueButtonClick); continueButton.addEventListener("click", handleContinueButtonClick); console.log('Continue按钮事件已绑定'); } } // 页面首次加载完成后绑定事件 document.addEventListener('DOMContentLoaded', bindContinueButton); // 监听pageshow事件:页面从BF Cache恢复时触发 window.addEventListener('pageshow', function(event) { // persisted属性为true表示页面从缓存中恢复 if (event.persisted) { console.log('页面从往返缓存恢复'); bindContinueButton(); } }); </script>
关键说明:
pageshow事件的event.persisted属性可以准确判断页面是否从BF Cache恢复,这是现代浏览器推荐的检测方式。- 每次页面显示(包括首次加载和回退恢复)都重新绑定事件,确保按钮的点击逻辑始终有效。
- 增加了按钮存在性检查,避免因DOM元素未加载完成导致的报错。
- 先移除已有监听再添加,防止重复绑定导致多次触发跳转。
内容的提问来源于stack exchange,提问作者Kelash
相关产品推荐
相关产品推荐

