How to remove the hash from [removed] (URL) with JavaScript without page refresh?

前端 未结 16 2981
无人及你
无人及你 2020-11-22 02:53

I have URL like: http://example.com#something, how do I remove #something, without causing the page to refresh?

I attempted the following

相关标签:
16条回答
  • 2020-11-22 02:57
    $(window).on('hashchange', function (e) {
        history.replaceState('', document.title, e.oldURL);
    });
    
    0 讨论(0)
  • 2020-11-22 02:57

    Here is another solution to change the location using href and clear the hash without scrolling.

    The magic solution is explained here. Specs here.

    const hash = window.location.hash;
    history.scrollRestoration = 'manual';
    window.location.href = hash;    
    history.pushState('', document.title, window.location.pathname);
    

    NOTE: The proposed API is now part of WhatWG HTML Living Standard

    0 讨论(0)
  • 2020-11-22 02:59
    const url = new URL(window.location);
    url.hash = '';
    history.replaceState(null, document.title, url);
    
    0 讨论(0)
  • 2020-11-22 03:04

    (Too many answers are redundant and outdated.) The best solution now is this:

    history.replaceState(null, null, ' ');
    
    0 讨论(0)
  • 2020-11-22 03:04

    Simple and elegant:

    history.replaceState({}, document.title, ".");  // replace / with . to keep url
    
    0 讨论(0)
  • 2020-11-22 03:04

    This will remove the trailing hash as well. eg: http://test.com/123#abc -> http://test.com/123

    if(window.history.pushState) {
        window.history.pushState('', '/', window.location.pathname)
    } else {
        window.location.hash = '';
    }
    
    0 讨论(0)
提交回复
热议问题