如果 window.history.back 不可能,则重定向页面
Redirect page if window.history.back isn't possible
我一直在使用浏览器历史记录返回页面。但是,由于 JS 无法可靠地读取用户历史记录,因此当没有历史记录时,我无法知道我的按钮不再起作用。
如果返回失败,我尝试使用这些方法来重定向页面:
window.history.back();
setTimeout(function () { window.location.href = "http://www.whosebug.com"; }, 500);
然而,这完全依赖于任意时间段,它可能适用于所有用户,也可能不适用于所有用户(并将其设置得足够高以保证它适用于每个人会给大多数人带来痛苦的缓慢体验)
在评论中建议我现在也尝试使用这些方面的一些不同尝试:
if (!window.history.back()) {
window.location.href = "http://www.whosebug.com";
}
但是window.history.back()
总是returnfalse
不管功能是否成功。我认为这是浏览器内置的安全功能。
有谁知道检测页面更改失败的方法,或者可以更优雅地解决此问题的其他方法吗?
我最终得到了一个相对有用(如果有点老套)的解决方案:
// On page load
if (history.length <= 1) {
/*
* This will only execute the first time the page (with absolutely no browser
* history, including browser splash screens that may add to the history)
* is loaded, it wont happen if you navigate back to the page
* so store the current page in local storage
*/
localStorage.setItem("root", document.location);
}
// Then execute some code only on the root
if (localStorage.getItem("root") == document.location) {
// Your code
}
一些潜在问题:
- 如果您需要同时打开多个此类页面,它将中断,因为加载的页面的第一个实例将检查第二个页面的根目录(除非您为该组页面自定义本地存储名称)
- 需要local storage which doesn't work on some of the (really) old browsers
- 这仅适用于具有 无 浏览器历史记录的页面,通常只有在新选项卡中打开页面或在外部 link 中单击 link =26=]。大多数浏览器都包含一个 splash-screen/home-page,它将添加到浏览器历史记录中。
我一直在使用浏览器历史记录返回页面。但是,由于 JS 无法可靠地读取用户历史记录,因此当没有历史记录时,我无法知道我的按钮不再起作用。
如果返回失败,我尝试使用这些方法来重定向页面:
window.history.back();
setTimeout(function () { window.location.href = "http://www.whosebug.com"; }, 500);
然而,这完全依赖于任意时间段,它可能适用于所有用户,也可能不适用于所有用户(并将其设置得足够高以保证它适用于每个人会给大多数人带来痛苦的缓慢体验)
在评论中建议我现在也尝试使用这些方面的一些不同尝试:
if (!window.history.back()) {
window.location.href = "http://www.whosebug.com";
}
但是window.history.back()
总是returnfalse
不管功能是否成功。我认为这是浏览器内置的安全功能。
有谁知道检测页面更改失败的方法,或者可以更优雅地解决此问题的其他方法吗?
我最终得到了一个相对有用(如果有点老套)的解决方案:
// On page load
if (history.length <= 1) {
/*
* This will only execute the first time the page (with absolutely no browser
* history, including browser splash screens that may add to the history)
* is loaded, it wont happen if you navigate back to the page
* so store the current page in local storage
*/
localStorage.setItem("root", document.location);
}
// Then execute some code only on the root
if (localStorage.getItem("root") == document.location) {
// Your code
}
一些潜在问题:
- 如果您需要同时打开多个此类页面,它将中断,因为加载的页面的第一个实例将检查第二个页面的根目录(除非您为该组页面自定义本地存储名称)
- 需要local storage which doesn't work on some of the (really) old browsers
- 这仅适用于具有 无 浏览器历史记录的页面,通常只有在新选项卡中打开页面或在外部 link 中单击 link =26=]。大多数浏览器都包含一个 splash-screen/home-page,它将添加到浏览器历史记录中。