Safari 14版本pageshow事件event.persisted始终为false求助
Safari 14.1 后退页面重新加载问题解决方案
你的核心问题是Safari 14.1及更早版本中,pageshow事件的event.persisted返回始终为false,且performance.getEntriesByType("navigation")的兼容性不足,导致判断条件无法触发。以下是针对性的解决办法:
方案一:兼容旧版导航检测API
旧版Safari支持已废弃的performance.navigation.type属性,其中值为2代表后退/前进导航,结合原有判断逻辑即可修复:
if (navigator.userAgent.includes("Safari") && !navigator.userAgent.includes("Chrome")) { window.addEventListener('pageshow', function(event) { // 兼容Safari 14.1:通过performance.navigation.type判断后退行为 const isBackForwardNav = performance.navigation.type === 2; if (event.persisted || isBackForwardNav) { location.reload(); } }, false); }
方案二:结合popstate事件辅助判断
部分旧版Safari在后退时会优先触发popstate事件,可通过状态变量标记后退行为,再在pageshow中校验:
if (navigator.userAgent.includes("Safari") && !navigator.userAgent.includes("Chrome")) { let isBackNavigation = false; window.addEventListener('popstate', () => { isBackNavigation = true; }); window.addEventListener('pageshow', function(event) { if (event.persisted || isBackNavigation) { location.reload(); isBackNavigation = false; // 重置状态,避免后续误触发 } }, false); }
方案三:强制禁用页面缓存
通过HTML meta标签禁止浏览器缓存页面,后退时会自动重新加载,无需JS判断:
<head> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> </head>
注意:此方案会增加服务器请求量,影响页面加载性能,仅在其他方案无效时使用。
内容的提问来源于stack exchange,提问作者avocado
相关产品推荐
相关产品推荐

