Skip to content

Instantly share code, notes, and snippets.

@brothertao
Created January 24, 2014 03:33
Show Gist options
  • Save brothertao/8591629 to your computer and use it in GitHub Desktop.
Save brothertao/8591629 to your computer and use it in GitHub Desktop.
当浏览器的history不好用的时候,可以试试这个。当然这种情况出现的概率很低
(function($) {
var key = 'history:mock';
var historyDb = {
cursor: null,
action: null,
urls: []
};
function saveState() {
sessionStorage.setItem(key, JSON.stringify(historyDb));
}
function redirect() {
window.location.href = historyDb.urls[historyDb.cursor];
return;
}
function init() {
var h = sessionStorage.getItem(key);
!!h && (historyDb = JSON.parse(h));
if (historyDb.action!==null) { //前进后退上下文中,不对urls和cursor修改
historyDb.action = null;
} else { // 退出前进后退上下文
var urls = historyDb.urls;
var href = window.location.href;
if (urls[historyDb.cursor] !== href) {
urls.splice(historyDb.cursor+1);
urls.push(window.location.href);
historyDb.cursor = urls.length-1;
};
}
saveState();
};
init();
$.history = {db: historyDb};
$.history.go = function(step) {
var cursor = historyDb.cursor+step;
if (cursor>historyDb.urls.length-1 || cursor<0) {
return;
} else {
historyDb.cursor = cursor;
};
historyDb.action = 'go';
saveState();
redirect();
}
})(jQuery)
@brothertao
Copy link
Author

要html5支持

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment