Javascript脚本之清除浏览器历史数据

简介

在某些数据查询页面,点击某条数据查看详细信息,如果此时列表数据有更新(新增、修改、删除等),当点击浏览器的返回按钮时,查看的数据仍然是旧的数据,原因是返回时,查看的是浏览器的缓冲数据,并不会从数据库中重新查询。为了解决这个问题,我研究出了一段可以避免这种脏数据的脚本,只需要在查询页面加入一段脚本即可。我将这段脚本写在了一个nohistory.js的文件中,在查询页面引入即可实现实时最新数据。

JavaScript脚本代码展示

/**

* 在引入该js文件时,可以传递model参数,表示刷新模式:

* strict或1:严格模式(默认值),所有点击后退或前进按钮的方式进入页面都会刷新

* loose或0:宽松模式,只针对点击某元素的方式离开页面才会刷新

* 示例:<script src="nohistory.js?model=0"></script>

* 注:该插件只对get(查询)请求方式有效!

*/

(function(id, refresh) {

var hisgory = performance.navigation.type === 2,

scripts = document.scripts,

src = scripts[scripts.length - 1].src,

// 宽松模式检测

loose = /model\s*=\s*(?:loose|0)/.test(src);

if (loose) {

document.write('<input type="hidden" id="' + id + '" autocomplete="on" />');

var element = document.getElementById(id);

function addEvent(e, type, fn) {

typetype = type.toLowerCase().replace(/^on/, "");

if (e.addEventListener) {

e.addEventListener(type, fn);

} else if (e.attachEvent) {

e.attachEvent("on" + type, fn);

} else {

e["on" + type] = fn; // IE5

}

}

function removeEvent(e, type, fn) {

typetype = type.toLowerCase().replace(/^on/, "");

if (e.removeEventListener) {

e.removeEventListener(type, fn);

} else if (e.detachEvent) {

e.detachEvent("on" + type, fn);

} else {

e["on" + type] = null; // IE5

}

}

function mark() {

element.value = "1";

}

var binded = false;

addEvent(window, "mousedown", function() {

if (!binded) {

binded = true;

addEvent(window, "beforeunload", mark);

}

});

addEvent(window, "mouseout", function(e) {

ee = e || window.event;

var tagName = e.target.tagName;

if (binded && (tagName == "BODY" || tagName == "HTML")) {

binded = false;

removeEvent(window, "beforeunload", mark);

}

});

// 排除“F5”和“Ctrl+R”刷新

addEvent(document, "keydown", function(e) {

ee = e || window.event;

if (e.keyCode == 116 || e.ctrlKey && e.keyCode == 82) {

removeEvent(window, "beforeunload", mark);

}

});

// Compatible IE

addEvent(document, "readystatechange", function() {

if (document.readyState === "complete" && element.value && hisgory) {

refresh();

}

});

} else if (hisgory) {

refresh();

}

})("nohistory_v2.0, code by [email protected] in 2017.12.07", new Function("location+=''"));

使用示例

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>浏览器返回、前进回到该页面自动刷新</title>

<script type="text/javascript" src="js/nohistory.js"></script>

</head>

<body>

...

</body>

</html>


 

猜你喜欢

转载自blog.csdn.net/qfchenjunbo/article/details/89337196