History.pushState(data,title,url) concatenates (instead of replacing) url to address bar if there is a trailing slash
Asked Answered
K

2

11

For example,

If I use the search bar from "www.site.com" I see "www.site.com/search", which is fine.

If I use the search bar from "www.site.com/events/" I see "www.site.com/events/search", which is silly.

Why does it do this? Is this the behavior or a history.js bug or my bug?

Krohn answered 6/4, 2012 at 15:23 Comment(0)
L
15

Give an example of what you are doing.

If your current URL in the address bar has the form: http://somesite.com/path/ And you pass pushState( null, null, 'newpath' ); in this case, the link will look like http://somesite.com/path/newpath but if you pass a parameter as: pushState( null, null, '/newpath' ), in this case would look like this: http://somesite.com/newpath

Lot answered 6/4, 2012 at 15:48 Comment(1)
This is VERY dangerous if your application will ever not be deployed in the root of the server! See my answer for a workaroundInadvertency
I
5

If your application is not deployed at the root (such as with a virtual directory, or just in a deeper hierarchy) then you'll end up screwing up the URL if you do history.pushState({}, '/newpath');

There's a couple alternatives :

1) Get your root path in a javascript variable that you can just prepend the URL to it. In this example window.ViewModel.rootPath is just an arbitrary place - just modify this for however you want to store global variables.

You will have to set the rootPath in script (example here for .NET).

<script>
    window.ViewModel.rootPath = "@Request.ApplicationPath";
</script>

history.pushState({}, window.ViewModel.rootPath + '/newpath');

2) Check if the URL ends with a / and if it does you need to go up 1 directory level. Note: This approach requires you to know the 'parent' directory of what you're posting - in this case YourAccount.

history.pushState({ mode: 'Club' }, '',
     (window.location.href.endsWith('/') ? '../' : '') +
      'YourAccount/ManageClub/' + id );

If the current URL is /preview/store/YourAccount then this will become ../YourAccount/ManageClub/123.

If the current URL is /preview/store/YourAccount/ then this will become YourAccount/ManageClub/123.

These with both end up at the same URL.

Inadvertency answered 28/10, 2015 at 2:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.