Safari 16.1中popstate事件失效问题咨询
Safari 16.1中popstate事件未触发的问题解决
问题背景
我需要在用户点击浏览器回退按钮时显示一张图片,之前的代码在Safari 15.5里运行正常,但升级到Safari 16.1后完全失效——点击回退按钮直接返回上一页,popstate事件根本没触发。测试代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <script> history.replaceState(null, null, null) history.pushState(null, null, null); window.addEventListener('popstate', function () { alert('fired'); }); </script> </head> <body>test</body> </html>
问题原因
Safari 16+对History API的处理逻辑做了优化:当连续调用replaceState和pushState且传入的state都是null时,浏览器会判定这些操作没有实际意义,直接合并或忽略,导致回退时跳过当前页面的state记录,自然不会触发popstate事件。
解决方案
给每个state传入唯一的标识值,让浏览器识别出不同的state状态,避免被优化合并。修改后的代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <script> // 给每个state设置唯一key,避免浏览器优化 history.replaceState({ page: 'initial' }, null, null); history.pushState({ page: 'current' }, null, null); window.addEventListener('popstate', function (event) { // 判断回退到初始state时触发逻辑 if (event.state?.page === 'initial') { alert('fired'); // 这里插入显示图片的逻辑,示例: const img = document.createElement('img'); img.src = '你的图片URL'; img.style.position = 'fixed'; img.style.top = '0'; img.style.left = '0'; document.body.appendChild(img); // 如果需要停留在当前页面,重新push一个state history.pushState({ page: 'current' }, null, null); } }); </script> </head> <body>test</body> </html>
补充说明
如果不需要阻止页面回退,只是在回退前触发显示图片的逻辑,可以去掉最后一行的history.pushState,但此时页面会正常回退,图片可能只会短暂显示,可根据需求调整。
内容的提问来源于stack exchange,提问作者nowa
相关产品推荐
相关产品推荐

