首页 > 关于history.pushState()的问题

关于history.pushState()的问题

在项目中我使用了 history.pushState()的方法来配合AJAX请求,改变页面的路径

history.pushState(null,null,'我的路径');

触发以后路径的确变了,连点几个以后,我点了浏览器的后退,
这时候内容变成以前的,但是页面url却没有变!
再点一次后退,url才变成上一页的,但是此时内容已经是上上页的了,怎么破?

用history.replaceState()这个方法的话,第一次点后退url没有变,但是内容后退了,
第二次点以后url才会和内容一起后退。但这时候内容永远是url的上一页。


我写了demo也是没问题的,刚刚发现问题在哪了,是我这个页面里有个iframe,我点击某个dom去改了iframe的src,同时也pushState,这时候第一次后退,没有触发onpopstate,我去掉对iframe的操作就没问题!求解


pushState顾名思义,意味着你要保存你的state的,不然浏览器也不知道后退之后的页面该长啥样
你需要将你页面的状态,传入history.pushState的第一个参数,标题传入第二个参数
然后你需要监听window的onpopstate事件,你绑定的state会在event对象上传给你

这段MDN的代码能说明问题:

window.onpopstate = function(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}

https://developer.mozilla.org/en-US/docs/Web/Events/popstate

【热门文章】
【热门文章】