还在学习中,记录一下在工作上遇到的问题
若有错误的地方欢迎指教,十分感谢
需求
在页面中实践 SPA新增自订义 query string,放到为 URL 中页面可以依据 query string 的内容去发 API实作步骤:
浏览本身提供了 URL、URLSearchParams 的 WebAPIs 可以使用
参考:URL、URLSearchParams
1. 拿取当前页面的 URL,加入 query string
const currentUrl = new URL(window.location.href);const searchParams = new URLSearchParams();searchParams.append('item', 100);currentUrl.search = searchParams;const address = `http://www.test.com/page${currentUrl.search}`;console.log(address); // http://www.test.com/page?item=100
URLSearchParams 还有提供很多方法可以对参数/值做事:
URLSearchParams.append() // 插入一个自定义的参数与值URLSearchParams.delete() // 删除指定参数及值URLSearchParams.get() // 取得指定查询的参数(第一个值)URLSearchParams.has() // 判断参数是否存在
2. 将自定义的 URL 加入到浏览器的历史纪录堆叠(history stack)
HTML5 提供了可以储存网页历史纪录的方法:history.pushState()
和 history.replaceState()
方法
两者差别在纪录堆叠的方式不同,细节可参考:History API
state:可储存一个 state 物件,并能在 onpopstate 事件中拿到该值
title:更新后页面的标题,目前浏览器会忽略,文件中建议给空字串
url:设定要更新历史纪录的 URL
// history.pushState(state, title, url);history.pushState(null, null, address);
遇到问题
被更换过的 URL 页面,若点击浏览器的上一页按钮却没有反应,但 URL 确实有被置换
查询文件后发现,浏览器对于新的URL并不会重新加载、检查存在与否
解决方式
使用浏览器提供的方法 window.onpopstate
Window.onpopstate
该方法会在会在历史纪录有发生变动时被触发(例如点击浏览器的上下一页按钮)一个 popstate event
我们就可以在事件中,加入自定义的内容,去判断当前状态是否需要进行页面重载
window.onpopstate = function(event) { if (event.state) return location.reload();}