【问题标题】:How to remove the hash from window.location (URL) with JavaScript without page refresh?如何在不刷新页面的情况下使用 JavaScript 从 window.location (URL) 中删除哈希?
【发布时间】:2010-11-26 16:59:46
【问题描述】:

我的 URL 类似于:http://example.com#something,如何删除#something,而不导致页面刷新?

我尝试了以下解决方案:

window.location.hash = '';

但是,这不会从 URL 中删除井号 #。

【问题讨论】:

  • 您真的要这样做吗?它会导致页面刷新。
  • 是否可以不刷新页面?
  • 这是可能的。 AJAX 历史库处理它。但这并不容易,几乎每个浏览器都必须以不同的方式完成。不是你想进入的东西。
  • 除了视觉效果之外,是否有任何考虑留下“#”?

标签: javascript window.location fragment-identifier


【解决方案1】:

如今,解决这个问题变得更加触手可及。 HTML5 History API 允许我们操纵地址栏以显示当前域中的任何 URL。

function removeHash () { 
    history.pushState("", document.title, window.location.pathname
                                                       + window.location.search);
}

工作演示:http://jsfiddle.net/AndyE/ycmPt/show/

这适用于 Chrome 9、Firefox 4、Safari 5、Opera 11.50和在 IE 10 中。对于不受支持的浏览器,您始终可以编写一个优雅的降级脚本,在可用的情况下使用它:

function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

因此,您可以摆脱井号,只是不是在所有浏览器中都可以——目前还没有。

注意:如果要替换浏览器历史记录中的当前页面,请使用replaceState()而不是pushState()。

【讨论】:

  • 使用这一行来确保您不会丢失查询字符串:history.pushState("", document.title, window.location.pathname + window.location.search);
  • @Phil:感谢您指出这一点,我已经相应地更新了答案。我太习惯使用漂亮的网址了。
  • 对于旧版本的 IE,您似乎需要使用 document.documentElement 而不是 document.body。看到这个答案stackoverflow.com/a/2717272/359048
  • 我建议使用 replaceState 而不是 pushState,以免在浏览器历史记录中创建额外的条目。
  • @santiagoarizti:你说得对,我也得出了同样的结论。我没有正确检查我编写的代码(7 年前!)并且错过了在删除哈希时我也在切换按钮的状态。由于您要手动更改哈希,我想您总是可以自己触发事件。
【解决方案2】:

最初的问题:

window.location.href.substr(0, window.location.href.indexOf('#'))

或

window.location.href.split('#')[0]

两者都将返回不带哈希或后面任何内容的 URL。

关于您的编辑:

对window.location 的任何更改都会触发页面刷新。您可以在不触发刷新的情况下更改 window.location.hash(尽管如果您的哈希与页面上的 id 匹配,窗口会跳转),但您无法摆脱哈希符号。选择哪个更糟...

最新答案

如何在不牺牲(完全重新加载或将井号留在那里)的情况下做到这一点的正确答案是down here。在这里留下这个答案是因为它是 2009 年的原始答案,而利用新浏览器 API 的正确答案是 1.5 年后给出的。

【讨论】:

  • 这完全是错误的,你可以改变 window.location.hash 并且它不会触发刷新。
  • @Evgeny -- 这就是我的回答。我明确地说更改 window.location.hash 不会触发刷新。 “您可以在不触发刷新的情况下更改 window.location.hash(尽管如果您的哈希与页面上的 id 匹配,窗口会跳转)”。
  • 没有页面重新加载 - 这是问题所在。这不是答案,因为它需要/强制重新加载页面!
  • 也认为不应该是✓answer
  • 这不是 OP 问题的答案。
【解决方案3】:

(太多答案是多余和过时的。)现在最好的解决方案是:

history.replaceState(null, null, ' ');

【讨论】:

  • 如果您想保留历史记录,请改用history.pushState(null, null, ' ')。
  • 解释为state 和title 参数传递null 的最终作用可能会有所帮助。
  • 这个问题和其他问题是它不会触发 onhashchange,即使哈希现在是空的,而之前它不是。
  • 在 TypeScript 中,第二个参数不允许为 null,因为该命令需要一个字符串。 Mozilla 建议使用空字符串。
  • 这种行为是否记录在某处?所有浏览器/版本都支持吗?
【解决方案4】:

简洁优雅:

history.replaceState({}, document.title, ".");  // replace / with . to keep url

【讨论】:

  • 如果您想留在同一目录中,请使用点而不是斜线
  • 请更新关于@vahanpwns 注释的答案,以使用. 而不是/。使用 / 将 url 更改为根路径。
  • 感谢您的回答,我的用例修改为history.replaceState({}, document.title, location.href.substr(0, location.href.length-location.hash.length));。
  • 这不会保留 url 查询。
  • 我的用例也是替换而不是推送,但这对我来说更有意义:history.replaceState(null, document.title, location.pathname + location.search);
【解决方案5】:

你可以这样做:

history.replaceState({}, document.title, window.location.href.split('#')[0]);

【讨论】:

  • 加星标的答案在这两种情况下都对我不起作用,但这个答案对我有用。谢谢!
【解决方案6】:

要删除哈希,您可以尝试使用此功能

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}

【讨论】:

    【解决方案7】:

    这也将删除尾随哈希。 例如:http://test.com/123#abc -> http://test.com/123

    if(window.history.pushState) {
        window.history.pushState('', '/', window.location.pathname)
    } else {
        window.location.hash = '';
    }
    

    【讨论】:

    • 这会删除 URL 中存在的所有查询参数 :(
    • @kevgathuku 您可以使用 location.search 将它们添加回来,例如:`window.history.pushState('', '/', window.location.pathname + window.location.search)`
    【解决方案8】:

    下面的呢?

    window.location.hash=' '

    请注意,我将哈希设置为单个空格,而不是空字符串。


    将哈希设置为无效锚也不会导致刷新。比如,

    window.location.hash='invalidtag'

    但是,我发现上述解决方案具有误导性。这似乎表明在给定位置上有一个具有给定名称的锚点,尽管没有。同时,使用空字符串会导致页面移动到顶部,这有时是不可接受的。使用空格还可以确保每当复制 URL 并添加书签并再次访问时,页面通常会位于顶部,并且空格将被忽略。

    而且,嘿,这是我在 StackOverflow 上的第一个答案。希望有人觉得它有用并且符合社区标准。

    【讨论】:

    • 将哈希设置为空格仍然保留 URL 末尾的 #,我认为目标是完全删除它。
    • 它在 URL 的末尾添加一个哈希。问题是如何删除它。
    • 是的,我们怎样才能删除#以及哈希字符串。
    【解决方案9】:
    const url = new URL(window.location);
    url.hash = '';
    history.replaceState(null, document.title, url);
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    【解决方案10】:
    <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>
    

    将此代码放在头部

    【讨论】:

      【解决方案11】:
      function removeLocationHash(){
          var noHashURL = window.location.href.replace(/#.*$/, '');
          window.history.replaceState('', document.title, noHashURL) 
      }
      
      window.addEventListener("load", function(){
          removeLocationHash();
      });
      

      【讨论】:

        【解决方案12】:

        我觉得这样会更安全

        if (window.history) {
            window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
        } else {
            window.location.hash = '';
        }
        

        【讨论】:

          【解决方案13】:
          $(window).on('hashchange', function (e) {
              history.replaceState('', document.title, e.oldURL);
          });
          

          【讨论】:

            【解决方案14】:

            这是另一种使用 href 更改位置并在不滚动的情况下清除哈希的解决方案。

            解释了神奇的解决方案here。规格here.

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

            注意:提议的 API 现在是 WhatWG HTML 生活标准的一部分

            【讨论】:

              【解决方案15】:

              根据上面给出的答案之一,使用这个:

              var scrollV, scrollH
              var loc = window.location;
              scrollV = document.body.scrollTop;
              scrollH = document.body.scrollLeft;
              if ("pushState" in history) {
                  history.pushState("", document.title, loc.pathname + loc.search);
              
                  // Restore the scroll offset
                  document.body.scrollTop = scrollV;
                  document.body.scrollLeft = scrollH;
              
              } else {
                  loc.hash = "";
              
                  // Restore the scroll offset
                  document.body.scrollTop = scrollV;
                  document.body.scrollLeft = scrollH;
              }
              

              【讨论】:

                【解决方案16】:

                尝试以下方法:

                window.history.back(1);
                

                【讨论】:

                • 如果用户直接访问包括哈希在内的 URL,这不会回答问题。
                • 当你只想创建一个指向上一页的链接,但链接隐藏在一堆 js 文件中时,这个技巧非常有用。
                • 正是我想要的。这可以完美地删除我的网络应用程序刚刚创建的主题标签,以便使用 javasript 函数返回的值。
                【解决方案17】:

                你可以用 null 代替 hash

                var urlWithoutHash = document.location.href.replace(location.hash , "" );
                

                【讨论】:

                • 问题询问“不会导致页面刷新”,但此方法确实会刷新页面。您应该在回答中注意这一事实,这样我们就不必浪费时间直接发现您回答的问题与我们在此处实际尝试回答的问题不同。
                • 不刷新页面。
                • 它不会刷新页面,因为它没有更新 URL。 replace 返回一个新的字符串,location.href 保持不变。只要你这样做location.href = urlWithouthHash,你就会得到刷新。
                猜你喜欢
                • 1970-01-01
                • 2011-03-07
                • 1970-01-01
                • 2019-10-23
                • 1970-01-01
                • 2011-01-18
                • 1970-01-01
                相关资源
                最近更新 更多