使用JavaScript无法删除URL中的片段

使用JavaScript无法删除URL中的片段

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

问题描述

背景:我有一个HTML页面,可以让您展开某些内容。由于只有一小部分页面需要加载以进行这种扩展,所以通过JavaScript完成,而不是通过指向新的URL / HTML页面。然而,作为奖励,用户能够固定到这样的扩展部分,即向其他人发送诸如



并拥有 foob​​ar类别将立即为其他用户打开。这可以使用parent.location.hash ='foobar',这样一部分就可以了。



现在的问题是:页面上的类别,我想再次清空URL片段,即转动更改为以更新固定链接显示。但是,使用 parent.location.hash ='<>会导致重新加载整个页面(例如,在Firefox 3中),我希望避免这种情况。使用 window.location.href ='/#'不会触发页面重新加载,但会在URL中留下看起来很前卫的#号。那么在流行的浏览器中有没有一种方法可以在不触发页面刷新的情况下JavaScript去除包含#符号的URL定位符? 解决方案

正如其他人所说, replaceState 在HTML5中可以用来移除URL片段。



以下是一个示例:

  //尽可能地去除片段,而不用在浏览器历史记录中添加条目:
window.location.replace(#);

//切掉HTML5中剩余的'#':
if(typeof window.history.replaceState =='function'){
history.replaceState({}, '',window.location.href.slice(0,-1));
}


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?

解决方案

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

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

09-03 15:04