Remove fragment in URL with JavaScript w/out causi

2019-01-08 22:15发布

Background: I have an HTML page which lets you expand certain content. As only small portions of the page need to be loaded for such an expansion, it's done via JavaScript, and not by directing to a new URL/ HTML page. However, as a bonus the user is able to permalink to such expanded sections, i.e. send someone else a URL like

http://example.com/#foobar

and have the "foobar" category be opened immediately for that other user. This works using parent.location.hash = 'foobar', so that part is fine.

Now the question: When the user closes such a category on the page, I want to empty the URL fragment again, i.e. turn http://example.com/#foobar into http://example.com/ to update the permalink display. However, doing so using parent.location.hash = '' causes a reload of the whole page (in Firefox 3, for instance), which I'd like to avoid. Using window.location.href = '/#' won't trigger a page reload, but leaves the somewhat unpretty-looking "#" sign in the URL. So is there a way in popular browsers to JavaScript-remove a URL anchor including the "#" sign without triggering a page refresh?

9条回答
别忘想泡老子
2楼-- · 2019-01-08 22:36

So use

parent.location.hash = '' first

then do

window.location.href=window.location.href.slice(0, -1);
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-08 22:36

Put this code on head section.

<script type="text/javascript">
    var uri = window.location.toString();
    if (uri.indexOf("?") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("?"));
        window.history.replaceState({}, document.title, clean_uri);
    }
</script>
查看更多
干净又极端
4楼-- · 2019-01-08 22:40

There is also another option instead of using hash, you could use javascript: void(0); Example: <a href="javascript:void(0);" class="open_div">Open Div</a>

I guess it also depends on when you need that kind of link, so you better check the following links:

How to use it: http://www.brightcherry.co.uk/scribbles/2010/04/25/javascript-how-to-remove-the-trailing-hash-in-a-url/ or check debate on what is better here: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

查看更多
贼婆χ
5楼-- · 2019-01-08 22:41

As others have mentioned, replaceState in HTML5 can be used to remove the URL fragment.

Here is an example:

// remove fragment as much as it can go without adding an entry in browser history:
window.location.replace("#");

// slice off the remaining '#' in HTML5:    
if (typeof window.history.replaceState == 'function') {
  history.replaceState({}, '', window.location.href.slice(0, -1));
}
查看更多
做个烂人
6楼-- · 2019-01-08 22:43

Sorry to say, but the answer is no if emptying location.hash doesn't accomplish the task !-)

查看更多
家丑人穷心不美
7楼-- · 2019-01-08 22:49

Since you are controlling the action on the hash value, why not just use a token that means "nothing", like "#_" or "#default".

查看更多
登录 后发表回答