HTML5实现无刷新修改URL的方法

2020-04-22 06:36:54易采站长站整理

一个字符串,代表新页面的标题。当前基本上所有浏览器都会忽略这个参数。
一个字符串,代表新页面的相对地址。(必须与当前页面处在同一个域。)

简单例子:假设当前页面为renfei.org/,打开控制台执行下面的 JavaScript 语句:


window.history.pushState({id: 1,name: "profile1"}, "My Profile", "/profile/"); //第一二参数可忽略设置为null

之后,地址栏的地址就会变成

renfei.org/profile/
,但同时浏览器不会刷新页面,甚至不会检测目标页面是否存在。

replaceState方法

有时,你希望不添加一个新记录,而是替换当前的记录,俩者区别在于 replaceState() 是修改了当前的历史记录项而不是新建一个。

replaceState和pushState原理一样使用也一样,最常用的方法:


window.history.replaceState({id: 1,name: "profile"},'下载','download?id=1');

特点:replaceState不会加入到历史记录里面,用history.go(-1)会跳过当前页面相当于是history.go(-2)。

popstate事件

当页面加载时,它可能会有一个非空的state对象。这可能发生在当页面设置一个state对象(使用pushState或者replaceState)之后用户重启了浏览器。当页面重新加载,页面将收到onload事件,但不会有popstate事件。然而,如果你读取history.state属性,将在popstate事件发生后得到这个state对象


var currentState = history.state; //得到当前页面设置的history.pushState的state对象参数值

调用

history.pushState() 
或者
history.replaceState() 
不会触发 popstate 事件。 popstate事件只会在浏览器某些行为下触发, 比如点击后退、前进按钮(或者在JavaScript中调用history.back()、history.forward()、history.go()方法)。

例子:假设当前页面地址是http://example.com/index.html


window.onpopstate = function(event) {
alert("location: " + document.location.href + ", state: " + JSON.stringify(event.state));//拿到history.state对象值
};
//绑定事件处理函数.
history.pushState({page: 1}, "title 1", "?page=100"); //添加并激活一个历史记录条目 http://example.com/index.html?page=100,条目索引为1 //history.state为{page: 1}
history.pushState({page: 2}, "title 2", "?page=200"); //添加并激活一个历史记录条目 http://example.com/index.html?page=200,条目索引为2
history.replaceState({page: 3}, "title 3", "?page=300"); //修改当前所在页面激活的历史记录条目 http://ex..?page=200 变为 http://ex..?page=300,条目索引为3