在 Javascript 中,如何“清除”背面(历史记录 -1)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8969878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:15:10  来源:igfitidea点击:

In Javascript, how do I "clear" the back (history -1)?

javascripthtmlcss

提问by TIMEX

When the user loads the page, I immediately do a window redirect to another location.

当用户加载页面时,我立即将窗口重定向到另一个位置。

The problem is, when the user clicks back, it'll go back to the page which does the redirect.

问题是,当用户点击返回时,它会返回到执行重定向的页面。

Can I "cancel" the history of the previous page? So that when the user clicks back, it goes back TWO pages instead?

我可以“取消”上一页的历史记录吗?这样当用户点击返回时,它会返回两页?

回答by xdazz

Instead of using window.location = url;to redirect,

而不是使用window.location = url;重定向,

try:

尝试:

window.location.replace(url);

after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

使用 replace() 后,当前页面将不会保存在会话历史记录中,这意味着用户将无法使用后退按钮导航到它。

回答by T.J. Crowder

You can use location.replaceto replace the current location entry (the redirect page) with the new one (the target). That requires that you do the redirection via JavaScript rather than with meta tags or a 302. E.g.:

您可以使用location.replace新的(目标)替换当前的位置条目(重定向页面)。这要求您通过 JavaScript 而不是使用元标记或 302 进行重定向。例如:

// In the redirecting page
location.replace("path/to/target/page");

Live example| Live example source

活生生的例子| 实时示例源

回答by Rebecca

For anyone coming across this page and looking for an AngularJS way to accomplish this (rather than javascript), use the $location service's replace() method (documentation) :

对于任何遇到此页面并寻找 AngularJS 方法来完成此操作(而不是 javascript)的人,请使用 $location 服务的 replace() 方法(文档):

Use $location.url('/newpath');or $location.path('/newpath');as you normally would to do the redirection in angular. And then just add $location.replace();right after it. Or you can chain the commands like this:

使用$location.url('/newpath');$location.path('/newpath');像往常一样以角度进行重定向。然后就$location.replace();在它后面添加。或者你可以像这样链接命令:

$location.url('/newpath').replace();