---
title: "HTML History API"
author: "mutongwu"
date: "2015-03-13T18:05:51Z"
tags: []
categories: ["Web前端"]
slug: "html-history-api"
draft: false
lastmod: "2015-03-13T18:05:51Z"
id: 2192175
url: "https://mutongwu.iteye.com/blog/2192175"
---

```js

// 替换当前浏览器history的最后一项记录。
history.replaceState([data], [title], [url]);

//在当前history的中，添加一项记录。
history.pushState([data], [title], [url]);

//1). In Firefox  data is limited to 640k characters.
//2). 参数 title 为字符串，当前浏览器一般忽略它。
//3). url 默认是相对当前路径。支持. / .. 路径表示。

```


**注意： 对history的修改，是受同源策略限制的。**


```js

//example:当前页面:www.google.com.hk
history.pushState(null, null, 'hello');

www.google.com.hk ----> www.google.com.hk/hello

history.pushState(null, null, '#jack');
www.google.com.hk/hello ----> www.google.com.hk/hello#jack

history.pushState(null, null, 'http:www.baidu.com');//ERROR

//后退、前进按钮，将触发该事件。
window.addEventListener('popstate', function(e) {
  // e.state is equal to the data-attribute of the last image we clicked
});

注意：在Android原生浏览器、Chrome (prior to v34) 、 Safari 上，页面第一次加载的时候，会自动触发该事件。

//历史记录变更就触发，包括：参数、hash、路径的变更。
window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

// 1. pushState / replaceState 不会触发该事件；
// 2. 用户的点击动作（后退、a链接）会触发事件。

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}

// 参考：
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
https://css-tricks.com/using-the-html5-history-api/

```