为什么在移动iOS Chrome浏览器中点击“返回”按钮时popstate不触发我的函数?

3

我想在新标签页中打开链接时,通过返回按钮能够返回到referrer页面。

const referrer = document.referrer;
const redirect = (e) => {
     if(e.state.goBack){
        window.location.href = window.location.href;
     }
 }

const _location = window.location.href
history.replaceState({goBack: true}, null, referrer);
history.pushState({}, null, _location);

window.addEventListener('popstate', redirect);

在 MacBook 和 Android 的 Chrome/Firefox 中一切正常。但是在 iPhone/iPad 上却无法工作,它只会返回到自己。即使我在重定向函数中添加一个警报,当我在 iPad 的 Chrome 上点击后退按钮时也不会出现警报 :(

感觉在 iPad 上点击后退按钮不会触发重定向函数。


https://jsfiddle.net/59xwafa3/3/ - kpe3000
在iPad上,当我点击返回按钮时,警告框没有弹出 :( - kpe3000
1个回答

2

我也遇到了同样的问题。我找到的解决方法是不使用replaceState,而是改用pushState:https://jsfiddle.net/6dayLhzs/1

const referrer = document.referrer;
const redirect = (e) => {
    if(e.state.goBack){
        window.location.href = window.location.href;
    }
 }

const _location = window.location.href
history.pushState({goBack: true}, null, referrer);
history.pushState({}, null, _location);

window.addEventListener('popstate', redirect);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接