如何在不更改浏览器历史记录的情况下更改url [英] how to change url without changing browser history

查看:79
本文介绍了如何在不更改浏览器历史记录的情况下更改url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在,我只知道如果我想更改URL而不重新加载整个页面,则必须使用HTML浏览器历史 API。

Until now, I only know that if I want to change URL without reloading the whole page i have to use HTML browser history 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

然后他去了我们有过滤器的产品清单。点击任何过滤器系统都会生成新的url,例如

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

内部只是呼叫

history.pushState({}, 'Title', link.href);

但是,它有一个问题。单击后退按钮将转到上一个过滤器。 我不想要此功能。我想要单击浏览器后退按钮,它应该转到当前页面之前的页面。在我们的例子中,假设

But, it has one problem. Clicking back button 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 current page. In our case, it is suppose to take to

https://www.example.com/aboutus

推荐答案

您正在寻找 replaceState(),它将替换历史记录中的当前位置,而不是推送新的位置,例如 pushState()

You're looking for replaceState(), it replaces the current position in the history instead of pushing a new one, like pushState() does

来自 MDN


history.replaceState()的操作与 history.pushState()
的操作完全相同,只是 replaceState ()修改当前历史记录条目,而不是
来创建一个新条目。

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.

replaceState()在您想要响应某些
用户操作而更新
状态对象或当前历史记录条目的URL时特别有用。

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.

请记住,某些功能在旧版浏览器上不可用。但是有一个
可以帮助您。

Remember, some functions are not available on older browsers. But there is a library that could help you out.

这篇关于如何在不更改浏览器历史记录的情况下更改url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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