有没有办法在不刷新页面的情况下更改浏览器的地址栏?

我在开发一个网络应用。在这里,我有一个名为“类别”的部分,每当用户单击其中一个类别时,更新面板就会加载适当的内容。

在用户单击类别之后,我要更改浏览器的地址栏 URL

www.mysite.com/products

比如说

www.mysite.com/products/{selectedCat}

而不刷新页面。
是否有某种 JavaScriptAPI 我可以用来实现这一点?

78173 次浏览

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.

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

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.

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

"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.

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