Skip to content

Instantly share code, notes, and snippets.

@suncn
Last active August 9, 2017 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suncn/39e9f4addbab05f8482ed41816d646ec to your computer and use it in GitHub Desktop.
Save suncn/39e9f4addbab05f8482ed41816d646ec to your computer and use it in GitHub Desktop.
HTML5 history API #history

history api

HTML5 history API只包括2个方法:history.pushState()和history.replaceState(),以及1个事件:window.onpopstate。

  • history.pushState()
  • history.replaceState()
  • window.onpopstate

history.pushState()

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/History/pushState

  • 语法

history.pushState(state, title, url);

  • demo
	var state = { 'page_id': 1, 'user_id': 5 };
	var title = 'Hello World';
	var url = 'hello-world.html';

	history.pushState(state, title, url);

history.history.replaceState()

类似pushState方法

history.pushState()

当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。

需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back())

不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。

  • demo
window.onpopstate = function(event) {
  alert("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(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment