使用 $location 手动更改 URL 时保留上一页

Preserve previous page when URL is changed manually with $location

本文关键字:URL 保留 一页 location 使用      更新时间:2023-09-26

我的控制器中有一个更改浏览器 URL 的函数,但是当用户单击后退按钮时,我需要保留真实的上一页。

例如:

用户位于/home 中并导航到/article1。当用户在页面中滚动时,我会使用以下方法更改 URL,例如更改为/article2:

$location.path('article2');

但是,如果用户按下留在/article2 中的后退浏览器按钮,则 url 将更改为/article1,我真的需要将导航重定向到/home。

我使用了以下代码:

var previousPage = document.referrer; // Get the previous location on page load
history.pushState({}, '', previousPage); // Alter the history adding the previous page

但它不起作用,因为在使用 $location 更改 url 时,历史记录状态会自动更改。

如何保留导航?

你可以这样使用

window.onpopstate = () => history.replaceState(history.state, 'gotohome', '/')

它将起作用,但是,我如何在不使用window.onpopstate的情况下更改上一页的URL,如果有人知道,请帮助我

您还可以在本地存储上一页以返回。我有一个应用程序,它有一个后退按钮,允许您返回您导航的页面。尝试这样的事情:

sessionStorage.previousPage = "mypage";
function goBack(){
 $location.path(sessionStorage.previousPage);
};