企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[https://developer.mozilla.org/zh-CN/docs/Web/API/History_API](https://developer.mozilla.org/zh-CN/docs/Web/API/History_API) [toc] ## 异步【误】 >[danger] 是因为pushState不会触发popState pushState是异步的,so,如果你直接在下面go,此时还没有记录,也就不会触发popState ``` window.onpopstate = function(event) { console.log(history.state) }; // location.href = '#123' history.pushState({a:1},'1','?123') history.pushState({b:1},'2','?234') // history.go(-1); //这样是无效的 document.documentElement.onclick = function(e){ history.go(-1) } ``` ## hash hash也会产生历史记录, 但如果你使用的是`location.href`(系列)这样设置的hash,**即使**同一个页面多次设置hash,只会产生一次记录,也就只会触发一次popstate(设置hash是**同步**的) ``` window.onpopstate = function(event) { console.log(1) // console.log(history.state) }; location.href = '#123' location.href='#hash1122' document.documentElement.onclick = function(e){ history.go(-1) } <<< 1 ``` 但如果你使用的是`pushState({...},'','#123')`设置hash,则调用几次就会产生几次记录 --- ## 你可以用 go() 方法载入到会话历史中的某一特定页面, 通过与当前页面相对位置来标志 (当前页面的相对位置标志为0). >history.pushState({},'','./abc') > >会改变url,但不会立刻加载,需要调用go()才会加载,才会触发onpopstate > >pushState支持相对路径 > >push的url只支持同源,否则报错 调用history.pushState()或者history.replaceState()不会触发popstate事件. popstate事件只会在浏览器某些行为下触发, 比如点击后退、前进按钮(或者在JavaScript中调用history.back()、history.forward()、history.go()方法). ``` window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; //绑定事件处理函数. history.pushState({page: 1}, "title 1", "?page=1"); //添加并激活一个历史记录条目 http://example.com/example.html?page=1,条目索引为1 history.pushState({page: 2}, "title 2", "?page=2"); //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2 history.replaceState({page: 3}, "title 3", "?page=3"); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为3 history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // 弹出 "location: http://example.com/example.html, state: null history.go(2); // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3} ```