Clearing URL hash

2019-01-22 06:47发布

Visit stackoverflow.com/#_=_ and window.location.hash evaluates to #_=_. Fine.

Now execute window.location.hash = '' to clear the hash, and the URL becomes stackoverflow.com/#. (Notice the trailing #.)

Why is the # in window.location.hash inconsistently included or excluded? How can the # be removed from the URL without reloading the page?

(MDN says

[the hash is] the part of the URL that follows the # symbol, including the # symbol.

but that is not true for in the case of an empty hash.)

4条回答
混吃等死
2楼-- · 2019-01-22 06:56

Answering to your first question:

According to the window.location doc in Mozilla.org: "the part of the URL that follows the # symbol, if there is one, including the # symbol. Empty string if the url does not contain # or has nothing after the #."

Curiously, that document was just updated on 4/8/2013. Not sure if that was added after you checked the documentation.

By the way (and in reference to the answers), the window.location.hash and pushState are different concepts although close related.

查看更多
在下西门庆
3楼-- · 2019-01-22 07:15

To answer the second question (removing the # without a page refresh):

history.pushState('', document.title, window.location.pathname);
查看更多
时光不老,我们不散
4楼-- · 2019-01-22 07:17

I've been dealing with the same issue about two weeks ago and my conclusion was that there was no good solution. There is no direct solution, removing the hash from URL always forced the browser to reload page, and even if there was an unpretty hack-like solution, I would rather have the hash at the end of url than using obscure solutions.

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-22 07:21

There are 2 things driving this behaviour:

  • "Setting the hash property navigates to the named anchor without reloading the document." (here)
  • "When you set the location object or any of its properties except hash[...]In JavaScript 1.1 and later, the effect of setting location depends on the user's setting for comparing a document to the original over the network." (here)

So basically, setting the hash property should never lead to a reload, setting any other property should lead to a reload (or perhaps an E-Tag/modified-since header check, depending on browser settings).

I would assume that for the sake of consistency, browser builders transform setting an empty hash, to setting '#' as hash. This way the url in the location bar does not lead to a reload. But this latter part is pure speculation.

查看更多
登录 后发表回答