• 微信号
  • 微信号
目录

javascript

您当前的位置:首页 > 我的笔记 > javascript>JS History对象:获取浏览历史

JS History对象:获取浏览历史

history.go()。

history 对象中的属性

下表中列举了 JavaScript history 对象中常用的属性及其描述:

属性 说明
length 返回浏览历史的数目,包含当前已经加载的页面。
scrollRestoration 利用浏览器特性,使我们在返回上一页或者下一页时,将页面滚动到之前浏览的位置,该属性有两个值,分别是 auto(表示滚动)与 **nual(表示不滚动)。
state 返回浏览器在当前 URL 下的状态信息,如果没有调用过 pushState() 或 replaceState() 方法,则返回默认值 null。

示例代码如下:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>JavaScript</title> 
</head> 
<body> 
<script type="text/javascript"> 
document.write(history.length + "<br>"); 
document.write(history.scrollRestoration + "<br>"); 
document.write(history.state + "<br>"); 
</script> 
</body> 
</html>

运行结果如下:

5

auto

null

history 对象中的方法

下表中列举了 JavaScript history 对象中常用的方法及其描述:

→ 按钮来实现同样的效果。go() 参照当前页面,根据给定参数,打开指定的历史记录,例如 -1 表示返回上一页,1 表示返回下一页。pushState() 向浏览器的历史记录中插入一条新的历史记录。replaceState() 使用指定的数据、名称和 URL 来替换当前历史记录。

示例代码如下:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>JavaScript</title> 
</head> 
<body> 
<button onclick="myBack()">back()</button> 
<button onclick="myForward()">forward()</button> 
<button onclick="myGo()">go()</button> 
<button onclick="myPushState()">pushState()</button> 
<button onclick="myReplaceState()">replaceState()</button> 
<script type="text/javascript"> 
function myBack(){ 
history.back(); 
} 
function myForward(){ 
history.forward(); 
} 
function myGo(){ 
var num = prompt('请输入一个整数', '1'); 
history.go(num); 
} 
function myPushState(){ 
var state = { 'page_id': 1, 'user_id': 5 } 
var title = 'JavaScript' 
var url = 'index.html' 
history.pushState(state, title, url) 
console.log(history.state); 
} 
function myReplaceState(){ 
var state = { 'page_id': 3, 'user_id': 5 } 
var title = 'history' 
var url = 'index.html' 
history.replaceState(state, title, url) 
console.log(history.state); 
} 
</script> 
</body> 
</html>