history对象和location对象
# history对象
在JavaScript中,window对象通过histor对象提供对浏览器的会话历史记录的访问
并且从HTML5开始,提供了对history栈中内容的操作
# history对象的方法和属性
跳转页面:
history.back():后退
history.forward():前进
history.go(num):前进或者后退基于本页面的第num个页面,前后由正负决定
状态属性:
history.state:当前历史记录状态对象,可以通过pushState存储或者replaceState修改
history.length:返回历史堆栈中页面个数
添加/修改状态方法:
history.pushState(stateObj,title,url);
stateObj:存在于当前历史记录的状态对象,是一个js对象,可以用来存储数据,通过history.state获取
title:标题,可写可忽略
URL:该参数定义了新的历史url记录,并且会显示在浏览器url上。然而要注意的是,浏览器并不会立即执行这个url
新的url可以是绝对路径,也可以是相对路径,但是新的url必须域当前url同源,否则会抛出异常。
示例:history.pushState({ a: n }, "shop", "?data=" + n);
pushState的优点在于:
以对象的形式在当前历史记录存储数据,可以存储的数据非常灵活
基于哈希的方式,要把所有相关的数据编码为短字符串。localStorage就只能存字符串
history.replaceState(stateObj,title,url):替换当前历史记录状态
事件:
popstate:每当活动的历史记录项发生改变时触发。注意push和replace不会触发,只有前进或者后退等使历史记录改变时才会触发。
hashchange:pushState绝对不会触发事件,即使新的url与旧的url仅哈希不同也是如此
Coding
<body> <button onclick="history.forward()">前进</button> <button onclick="history.back()">后退</button> <button onclick="history.go(1)">go 1</button> <button onclick="history.go(-1)">go -1</button> <button id="btn">pushstate</button> <script> var btn = document.querySelector("#btn"); var n = 0; btn.onclick = function () { n++; history.pushState({ a: n }, "shop", "?data=" + n); console.log("当前历史记录状态对象state:",history.state); console.log("历史堆栈中页面个数:"+history.length); history.replaceState("修改后:",{a:"change"},"shop1","?data=" + n); } </script> </body>
初始效果:

点击pushSatate:

# location对象
window.location:只读属性其中包含有关文档的当前位置的信息
虽然window.location一个只读location对象,但是设置一个DOMString.
因此,window.location ="url"与location.href="url"同义
location对象属性与方法:
.href="url":加载url
.replace("url"):效果与href相同。重新加载页面并将window.location.pathname插入到hash
.assign("url"):加新新的文档。效果与href相同
区别:
replace不产生新的浏览历史记录,href和assign会产生
因此,现在replace时候,浏览历史记录将不能后退

浙公网安备 33010602011771号