Angular platformLocation pushState not working

徘徊边缘 提交于 2019-12-11 18:43:07

问题


I want to inject a new state to browser history when the platform is loaded for the 1st time so when the user clicks browser back button it should land to the home page of the app.

I tried to add new state using 1. PlatformLocation pushState() 2. window.history.pushState()

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

I even tried giving full URL

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

It does add a new state to browser history but when I click browser back button, nothing happens i.e. I am still in the same page but only the newly added state is removed from the browser history.


回答1:


I already answered this in your other question here: https://stackoverflow.com/a/55511843/11289490

When you call to the history.pushState , it only adds one page to the history with the url you want, but It doesn't load the webpage or check if it exists.

If you want to load the home page when you navigate back you can do something like this :

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

It adds a history with the url base and then add the complete url in the history.



来源:https://stackoverflow.com/questions/55494629/angular-platformlocation-pushstate-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!