javascript 如何在不更改浏览器历史记录的情况下更改 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20937280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to change url without changing browser history
提问by Paritosh Piplewar
Until now, I only know that if I want to change URL without reloading the whole page i have to use HTML browser historyAPI.
到目前为止,我只知道如果我想在不重新加载整个页面的情况下更改 URL,我必须使用 HTML 浏览器历史API。
I am using this concept in my website. Let's take example. Let suppose user is on this page
我在我的网站中使用了这个概念。让我们举个例子。假设用户在此页面上
https://www.example.com/aboutus
and then he goes to product listing in which we have filters. On clicking any filters system generates new url something like this
然后他转到我们有过滤器的产品列表。单击任何过滤器系统会生成类似这样的新网址
https://www.example.com/products?brands[]=song&brands[]=samsung&condition[]=new
Internally it is just calling
在内部它只是调用
history.pushState({}, 'Title', link.href);
But, it has one problem. Clicking backbutton takes to the previous filter. I dont want this functionality. I want , on clicking browser back button it should take to the page which is before currentpage. In our case, it is suppose to take to
但是,它有一个问题。单击back按钮将转到上一个过滤器。我不想要这个功能。我想,在单击浏览器后退按钮时,它应该转到页面之前的current页面。在我们的例子中,假设需要
https://www.example.com/aboutus
Thanks.
谢谢。
回答by adeneo
You're looking for replaceState(), it replaces the current position in the history instead of pushing a new one, like pushState()does
你要找的replaceState(),它代替了历史的当前位置,而不是推一个新的,像pushState()做
from MDN
来自MDN
history.replaceState()operates exactly likehistory.pushState()except thatreplaceState()modifies the current history entry instead of creating a new one.
replaceState()is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
history.replaceState()操作完全一样,history.pushState()除了replaceState()修改当前历史条目而不是创建新历史条目。
replaceState()当您想要更新当前历史条目的状态对象或 URL 以响应某些用户操作时,它特别有用。
Remember, some functions are not available on older browsers. But there is a librarythat could help you out.
请记住,某些功能在较旧的浏览器上不可用。但是有一个图书馆可以帮助你。

