Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

网页后退不刷新的N种解决方案 #17

Open
rico-c opened this issue Dec 17, 2018 · 1 comment
Open

网页后退不刷新的N种解决方案 #17

rico-c opened this issue Dec 17, 2018 · 1 comment
Labels

Comments

@rico-c
Copy link
Owner

rico-c commented Dec 17, 2018

正常在需要做页面后退操作时,可以通过调用history对象的go方法和back方法来控制页面后退,

window.history.go(-1);
window.history.back();

但是在部分移动端浏览器及webview中,页面实现了后退但是并没有刷新,而是使用了缓存。

这里总结了几种强制回退页面后刷新上一页的方法。

方案一:主动跳转至来源页

A页面打开B页面时,在B页面中document.referrer为A页面,通过主动跳转至document.referrer可以实现刷新上一页,但是副作用为会额外生成历史记录,导致再次点击后退时又回到当前页面。

window.location.href = document.referrer
兼容性:

image

方案二:监听页面pageshow事件

A页面打开B页面时,在A页面监听pageshow事件,当由B页面退回至A页面时会触发pageshow事件。

window.addEventListener('pageshow', function(e) {
   if (e.persisted) {
      window.location.reload();
   }
});
兼容性:

image

方案三:使用History对象修改当前历史记录

A页面打开B页面时,先替换当前历史记录点,然后再打开B页面。

var  json={time:newDate().getTime()};
window.history.replaceState(json,"",window.location.href+"&t="+newDate().getTime());
window.location.href= url;
兼容性:

image

方案四:

如果是在自家公司的APP中,可以通过与APP约定一个字段拼接在URL中,当APP检测到该字段时强制在APP层面触发刷新页面。

@rao3235970
Copy link

学习了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants