Angular platformLocation pushState not working

2019-08-17 18:06发布

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条回答
Fickle 薄情
2楼-- · 2019-08-17 18:55

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.

查看更多
登录 后发表回答