温馨提示×

location.href跳转时如何保留历史记录

小樊
82
2024-06-27 20:32:20
栏目: 编程语言

可以使用pushState方法来实现在使用location.href跳转时保留历史记录。pushState方法可以向浏览器的会话历史堆栈中添加一条记录,这样就可以在跳转后通过浏览器的前进和后退按钮来访问之前的页面。

示例代码如下:

// 在跳转之前调用pushState方法
window.history.pushState(null, null, "new-url");

// 使用location.href跳转
location.href = "new-url";

在上述代码中,先使用pushState方法将新的URL添加到历史记录中,然后再使用location.href进行跳转。这样就可以实现在跳转时保留历史记录。

0