【发布时间】:2021-12-02 22:29:59
【问题描述】:
我这里有这行代码:
if(window.location.search == "?mytoken=abc") {
window.history.replaceState(null, '', window.location.pathname);
}
此代码的作用是检查查询参数 mytoken 是否存在,如果存在,则替换没有查询参数的当前页面,这样可以完美运行。
但我确实注意到我的浏览器历史记录中确实有 2 个历史记录项,一个带有查询参数,另一个没有查询参数。我正在寻找从浏览器历史记录中删除带有查询参数的项目。这可能吗?
我在我的项目中找到了这段代码,如果有帮助的话:
history.listen((newLocation, action) => {
if (action === "PUSH") {
if (
newLocation.pathname !== this.currentPathname ||
newLocation.search !== this.currentSearch
) {
// Save new location
this.currentPathname = newLocation.pathname;
this.currentSearch = newLocation.search;
// Clone location object and push it to history
history.push({
pathname: newLocation.pathname,
search: newLocation.search,
});
}
} else {
// Send user back if they try to navigate back
history.go(1);
}
});
每次出现新页面时都会调用它。
【问题讨论】:
-
无法删除或修改过去的浏览器历史记录状态,但您可以使用自己的自定义对象来模拟历史记录,您可以完全控制这些状态。请查看the top answer here 以获取此方法的示例
标签: reactjs