使用 JavaScript 删除 URL 中的片段,不会导致页面重新加载 [英] Remove fragment in URL with JavaScript w/out causing page reload

查看:15
本文介绍了使用 JavaScript 删除 URL 中的片段,不会导致页面重新加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我有一个 HTML 页面,可以让您扩展某些内容.由于这种扩展只需要加载页面的一小部分,它是通过 JavaScript 完成的,而不是通过定向到新的 URL/HTML 页面.但是,作为奖励,用户可以永久链接到此类扩展部分,即向其他人发送类似

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

并立即为该其他用户打开foobar"类别.这可以使用 parent.location.hash = '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.

现在的问题是:当用户在页面上关闭了这样一个类别时,我想再次清空URL片段,即转http://example.com/#foobarhttp://example.com/ 更新永久链接显示.但是,使用 parent.location.hash = '' 这样做会导致整个页面的重新加载(例如,在 Firefox 3 中),我想避免这种情况.使用 window.location.href = '/#' 不会触发页面重新加载,但会在 URL 中留下看起来有些不美观的#"符号.那么在流行的浏览器中是否有一种方法可以在不触发页面刷新的情况下通过 JavaScript 删除包含#"符号的 URL 锚点?

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?

推荐答案

正如其他人提到的,replaceState 可用于删除 URL 片段.

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

这是一个例子:

// 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));
}

这篇关于使用 JavaScript 删除 URL 中的片段,不会导致页面重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆