Clearing URL hash

后端 未结 3 1068
难免孤独
难免孤独 2020-12-13 18:54

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

Now execute window.location.hash = \'\'

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 19:08

    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.

提交回复
热议问题