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?
In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.
The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page.
The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.
The History. replaceState() method modifies the current history entry, replacing it with the state object and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With