每次ajax操作會往iframe.src的問號後附加一個數字以記錄曆史。點擊後退按鈕,iframe的onload事件中擷取iframe的url,根據問號後的數字去取記錄。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>0</title>
</head>
<body>
<input type="button" value="加1" onclick="add()" />
<div id="info" style="border:red 1px solid;width:200px;padding:10px;margin:5px;">0</div>
</body>
</html>
<script >
/**
* history.js v0.2
* Copyright (c) 2011 snandy
*
* 1 使用iframe,通過修改iframe.src產生曆史
* 2 IE6/7/8/9/10/Firefox/Safari/Chrome/Opera 都支援
*
*/
History = function() {
var
iframe,
// 儲存記錄
list = [],
// 記錄索引
index = 0,
pushing;
iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function() {
if(pushing) return;
var url= this.contentWindow.location.href;
if(url.indexOf('?')>-1) {
var idx = url.substr(url.indexOf('?')+1);
get(idx);
}
}
document.body.appendChild(iframe);
function push(data) {
if(typeof data !== 'object') return;
if(typeof data.param == undefined || typeof data.func !== 'function') return;
list[index] = data;
updateIframe();
pushing = true;
index++;
setTimeout(function(){
pushing = false;
}, 100);
}
function updateIframe() {
iframe.src = 'blank.html?' + index;
}
function get(idx) {
var item, param, func, scope;
if(idx != index) {
item = list[idx];
if(item) {
param = item.param;
func = item.func;
scope = item.scope;
func.call(scope, param);
}
}
}
return {
push : push
};
}();
</script>
<script>
var info = document.getElementById('info');
var i = 1;
function add() {
info.innerHTML = i;
document.title = i;
var data = {
param : i,
func : func
};
History.push(data);
i++;
}
History.push({param:0, func: func});
function func(i) {
info.innerHTML = i;
document.title = i;
}
</script>
<!DOCTYPE HTML>
<html>
<head>
<title>blank.html</title>
</head>
<body>
</body>
</html>