首页 > 解决方案 > Angular platformLocation pushState 不起作用

问题描述

我想在第一次加载平台时向浏览器历史记录注入一个新状态,因此当用户单击浏览器后退按钮时,它应该登陆应用程序的主页。

我尝试使用 1. PlatformLocation pushState() 2. window.history.pushState() 添加新状态

location.pushState(null, 'home', 'home');
// window.history.pushState(null, 'home', 'home');

我什至尝试给出完整的 URL

location.pushState(null, 'home', 'http://localhost:4200/home');
// window.history.pushState(null, 'home', 'http://localhost:4200/home');

它确实向浏览器历史记录添加了一个新状态,但是当我单击浏览器后退按钮时,什么也没有发生,即我仍在同一页面中,但只有新添加的状态从浏览器历史记录中删除。

标签: javascriptangularbrowserhtml5-history

解决方案


我已经在您的其他问题中回答了这个问题:https ://stackoverflow.com/a/55511843/11289490

当您调用 时history.pushState,它只会在历史记录中添加一个带有您想要的 url 的页面,但它不会加载网页或检查它是否存在。

如果您想在返回时加载主页,您可以执行以下操作:

 let locat = location.href;
    if (!!window.location.pathname && window.location.pathname !== '/') {
        history.replaceState(null,null,location.origin);
        history.pushState(null, null,locat);
    }

它使用 url 基础添加历史记录,然后在历史记录中添加完整的 url。


推荐阅读