Is there a way to change the browser's address bar without refreshing the page?

99封情书 提交于 2019-11-26 01:48:45

问题


I\'m developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content.

After the user clicked the category I want to change the browser\'s address bar url from

www.mysite.com/products 

to something like

www.mysite.com/products/{selectedCat} 

without refreshing the page.
Is there some kind of JavaScript API I can use to achieve this?


回答1:


With HTML5 you can modify the url without reloading:

If you want to make a new post in the browser's history (i.e. back button will work)

window.history.pushState('Object', 'Title', '/new-url');

If you just want to change the url without being able to go back

window.history.replaceState('Object', 'Title', '/another-new-url');

The object can be used for ajax navigation:

window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');

window.onpopstate = function (e) {
  var id = e.state.id;
  load_item(id);
};

Read more here: http://www.w3.org/TR/html5-author/history.html

A fallback sollution: https://github.com/browserstate/history.js




回答2:


To add to what the guys have already said edit the window.location.hash property to match the URL you want in your onclick function.

window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name



回答3:


I believe directly manipulating the address bar to a completely different url without moving to that url isn't allowed for security reasons, if you are happy with it being

www.mysite.com/products/#{selectedCat}

i.e. an anchor style link within the same page then look into the various history/"back button" scripts that are now present in most javascript libraries.

The mention of update panel leads me to guess you are using asp.net, in that case the asp.net ajax history control is a good place to start




回答4:


I don't think this is possible (at least changing to a totally different address), as it would be an unintuitive misuse of the address bar, and could promote phishing attacks.




回答5:


This cannot be done the way you're saying it. The method suggested by somej.net is the closest you can get. It's actually very common practice in the AJAX age. Even Gmail uses this.




回答6:


"window.location.hash"

as suggested by sanchothefat should be the one and only way of doing it. Because all the places that I have seen this feature, it's all the time after the # in URL.



来源:https://stackoverflow.com/questions/352343/is-there-a-way-to-change-the-browsers-address-bar-without-refreshing-the-page

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