imuncle.github.io
imuncle.github.io copied to clipboard
修改url而不刷新页面
trafficstars
最近有用户反映gitblog中的用户登录功能非常不稳定,有时能登录,有时不能登录。
看似是个小问题,结果自闭了两天。仔细debug发现是如下代码出了问题:
var token = getUrlParam('access_token');
if(token != undefined && token != null) {
window.localStorage.clear();
window.localStorage.setItem("access_token",token);
window.location.href = window.location.origin + window.location.pathname + "?id="+getUrlParam('id');
}
window.localStorage.setItem("access_token",token)这句话执行需要一定的时间,而JavaScript默认支持异步通信,所以token还没有存储进localStorage页面就已经跳转了,导致登录失败。
其实不跳转问题也不是很大,但用户的access_token直接显示在浏览器的url中总感觉有些不妥当,所以才进行跳转。
所以其实只要能将url中的access_token去掉就行了。
history.pushState()
隆重介绍HTML5 新增的API,可以在不刷新页面的情况下新增一条历史记录,同时更改url中的内容。
这个函数接受三个参数:
- state:一个与指定网址相关的状态对象,pushstate事件触发时,该对象会传入回调函数。如果不需要这个对象,此处可以填null。
- title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。
- url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。
所以我上面的代码修改如下:
var token = getUrlParam('access_token');
if(token != undefined && token != null) {
window.localStorage.clear();
window.localStorage.setItem("access_token",token);
history.pushState(null, config.title, 'content.html?id='+getUrlParam('id'));
}
history.replaceState()
但是上面的代码还有个小问题,在移动端操作的时候,登录后退出网页会回退到含有access_token的url页面,这样用户在退出的时候会多点一次退出,用户体验不佳,所以我把history.pushState()换成了history.replaceState()。修改后的代码如下:
var token = getUrlParam('access_token');
if(token != undefined && token != null) {
window.localStorage.clear();
window.localStorage.setItem("access_token",token);
history.replaceState(null, config.title, 'content.html?id='+getUrlParam('id'));
}
经测试,完美解决!