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

旧城冷巷雨未停 提交于 2021-02-07 05:46:20

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/10045540/history-pushstatedata-title-url-concatenates-instead-of-replacing-url-to-add

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