如何控制浏览器Url显示、监听Url变化
涉及知识点:浏览器事件
浏览器回退功能涉及到的相关API:
pushState
方法popstate
事件
需求
- 根据用户的查询条件,控制当前浏览器的url显示。
- 通过点击浏览器的回退按钮可以返回上一条的搜索条件。
基本思路
-
在点击搜索时,将搜索条件添加到浏览器的URL中,并向历史记录中新增一条数据
let searchContent = docoment.querySelector("#input"); if(window?.history?.pushState){ history.pushState(null,null,`?${searchContent}`) }
-
点击回退按钮时,通过URL获取到搜索条件,作为请求参数传递给后台
window.addEventListener('popstate',handlePopstate,null); function handlePopState(){ let decodeURI = decodeURIComponent(location.href); if (decodeURI.includes("?")) { let historyInput = decodeURI.split("?")[1]; let param = histortInput; .... // 进行搜素之后的相关操作 } }
相关API
pushState
-
MDN链接:https://developer.mozilla.org/zh-CN/docs/Web/API/History/pushState
-
作用:向当前浏览器会话的历史堆栈中添加一个状态
-
语法:
history.pushState(state,title[,url])
-
说明:使用
pushState
() 和location,href
基本是一致的,都会在当前浏览器会话中新增一条历史记录。 -
示例:
const state = {"submit_id":1}; const title = ''; const url="?.content"; history.pushState(state,title,url);
popstate
-
MDN链接:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/popstate_event
-
作用:当活动的历史记录发生变化时,将会触发
popstate
事件 -
触发条件
- 用户主动触发:点击浏览器的后退、前进按钮
- 代码触发:
history.back()
;history.go()
;history.forword()
方法等
-
说明:如果通过调用
history.pushState()
或者history.replaceState()
触发历史记录的修改,则不会触发popState
事件。 -
示例:
window.addEventListener('popstate', (event) => { console.log("location: " + document.location + ", state: " + JSON.stringify(event.state)); }); history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // Logs "location: http://example.com/example.html, state: null history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
参考链接:
- 通过
onpopstate()
监控浏览器前进后退数据:https://newsn.net/say/history-popstate.html