当cookie更改时,html页面如何自动重新加载?
我在主html页面中有这段代码:
body onload="set_style_from_cookie()"
当我从另一个页面更改主html页面的样式时,主页如何检测到此更改并自动重新加载?
答案 0 :(得分:0)
这个会起作用:
我只是包含了一个定时间隔来检查cookie是否已更改:
现在,如果您打开另一个窗口,它也会更新!
在此演示中仅涉及背景颜色。但你可以改变它并添加你需要的风格。
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<style type="text/css">
</style>
<script type="text/javascript">
function cookieWrite(name,value,days){var expires=""; if(days){var date=new Date(); date.setTime(date.getTime()+(days*86400000)); expires="; expires="+date.toUTCString();} document.cookie=name+"="+value+expires+"; path=/";}
function cookieRead(name){var n=name+"="; var ca=document.cookie.split(";"); for(var i=0; i<ca.length; i++){var c=ca[i]; while(c.charAt(0)==" "){c=c.substring(1,c.length);} if(c.indexOf(n)==0){return c.substring(n.length,c.length);}} return "";}
function cookieDelete(name){if(!name){var ca=document.cookie.split(";"); for(var i=0;i<ca.length; i++){var cv=ca[i].split("="); cookieWrite(cv[0],"",-1);}}else{cookieWrite(name,"",-1);}}
var mybgcolor="";
var cookieIntervall=setInterval(monitorCookie, 2000);
function set_style_from_cookie(bgcolor){
if(typeof bgcolor=="undefined"){bgcolor=cookieRead("backgroundColor");}
cookieWrite("backgroundColor", bgcolor, 7);
document.body.style.backgroundColor=bgcolor;
mybgcolor=bgcolor;
}
function monitorCookie(){
var bgcolor=cookieRead("backgroundColor");
if(mybgcolor!=bgcolor) set_style_from_cookie(bgcolor);
};
window.addEventListener("load",function(){set_style_from_cookie();},false);
</script>
</head>
<body>
<div> <button type="button" onclick="set_style_from_cookie('blue')">BLUE</button> </div>
<div> <button type="button" onclick="set_style_from_cookie('black')">BLACK</button> </div>
<div> <button type="button" onclick="set_style_from_cookie('white')">WHITE</button> </div>
<div> <button type="button" onclick="set_style_from_cookie('red')">RED</button> </div>
<div> <button type="button" onclick="set_style_from_cookie('yellow')">YELLOW</button> </div>
<hr />
<div>refresh page to see that the BG-color will be read from cookie</div>
</body>
</html>
答案 1 :(得分:0)
制作一个这样的函数,每隔0.1 seconds
//keep track of our cookie
var cookieRegistry = [];
function listenCookieChange(cookieName, callback) {
setInterval(function() {
if (cookieRegistry[cookieName]) {
if (readCookie(cookieName) != cookieRegistry[cookieName]) {
// update registry so we dont get triggered again
cookieRegistry[cookieName] = readCookie(cookieName);
return callback();
}
} else {
cookieRegistry[cookieName] = readCookie(cookieName);
}
}, 100);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
绑定它
listenCookieChange('cookiename', function() {
Location.reload();
});
然而,这将每秒执行此脚本10x
,因此您可能想要更改此内容。为此,请更改“100
”。 (如果你将其改为1000
,它将每秒检查一次)。