我希望在用户进入页面时创建一个运行jQuery脚本的页面,即使用户离开页面或关闭浏览器,查询也会运行。这可能吗?
if(localStorage.getItem("counter")){
if((localStorage.getItem("counter") >= 300) || (localStorage.getItem("counter") <= 0)){
var value = 300;
}else{
var value = localStorage.getItem("counter");
}
}else{
var value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function (){
if(value <= 0){
localStorage.setItem("counter", 0);
value = 0;
$( ".exit" ).trigger( "click" );
}else{
value = parseInt(value)-1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function (){counter();}, 1000);
这是我的剧本。有关详细信息,这是300的倒计时,当用户进入页面时,即使用户离开页面直到达到0,我也希望它能够运行。
答案 0 :(得分:0)
我敢回答你的问题,但希望这会对你有所帮助。此选项卡关闭后,没有机会运行此js代码,但您可以通过设置每个间隔周期和用户设置的 time_leave 来记住用户离开您网站的时间使用onbeforeunload离开您的网站:
var value;
if (localStorage.getItem('counter')) {
if ((localStorage.getItem('counter') >= 300) || (localStorage.getItem('counter') <= 0)) {
value = 300;
} else {
value = getElaspedTime();
}
} else {
value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value <= 0) {
localStorage.setItem('counter', 0);
value = 0;
//$('.exit').trigger('click');
} else {
value = parseInt(value) - 1;
localStorage.setItem('counter', value);
}
document.getElementById('divCounter').innerHTML = value;
// set "departure"-time
localStorage.setItem('time_leave', (new Date()).getTime());
};
function getElaspedTime() {
var now = new Date();
var timeLeft = + localStorage.getItem('time_leave');
timeLeft = new Date(timeLeft);
var passedSecs = (now.getTime() - timeLeft.getTime()) / 1000;
return parseInt(localStorage.getItem('counter')) - parseInt(passedSecs);
}
window.onbeforeunload = function(){
// set "departure"-time when user closes the tap
localStorage.setItem('time_leave', (new Date()).getTime());
};
var interval = setInterval(function () {
counter();
}, 1000);