Javascript定时重定向

Javascript timed redirect

本文关键字:重定向 定时 Javascript      更新时间:2023-09-26

我已经设置了一个基于重定向的重定向,无论用户是否在页面上处于活动状态。多亏了这个教程,我有99%的工作。只有一个功能我被卡住了。

JS是google chrome扩展的一部分。

页面处于非活动状态2秒后会弹出重定向警告,如果在5秒内没有其他活动,则页面会重定向到google.com(使用google.com仅用于测试目的)。

重定向到google.com后,计时器在2秒后再次启动——我不想这样。

我只希望计时器在用户在google.com上活动时启动(即触摸屏幕)。

我需要在某个地方添加一个额外的stopTimer功能吗?

我基本上希望计时器出现在主页之外的每一个页面上(在本例中为google.com)

到目前为止,我的代码-我已经创建了一个JS Fiddle;

谷歌重定向在JS fiddle中不起作用,但在我的生活环境中起作用。

var div = document.createElement("div");
div.style.display = "none";
div.style.height = "18em";
div.style.width = "30em";
div.style.marginTop = "-9em";
div.style.marginLeft = "-15em";
div.style.background = "#f2dede";
div.style.color = "black";
div.style.position = "absolute";
div.style.padding = "20px";
div.style.top = "50%";
div.style.left = "50%";
div.style.border = "5px solid #ebccd1";
div.style.borderRadius = "20px";
div.style.textAlign = "center";
div.style.zIndex = "9999";
document.body.appendChild(div);
var timeoutID;
var timerID;
var idleTimeout = 5; 
var idleSecondsTimer = null;
var idleSecondsCounter = 0;
function setup() {
    this.addEventListener("mousemove", resetTimer, false);
    this.addEventListener("mousedown", resetTimer, false);
    this.addEventListener("keypress", resetTimer, false);
    this.addEventListener("DOMMouseScroll", resetTimer, false);
    this.addEventListener("mousewheel", resetTimer, false);
    this.addEventListener("touchmove", resetTimer, false);
    this.addEventListener("MSPointerMove", resetTimer, false);
    startTimer();
}
setup();
function startTimer() {
    // wait 2 seconds before calling goInactive
    timeoutID = setTimeout(goInactive, 2000);
}
function resetTimer(e) {
    clearTimeout(timeoutID);
    clearTimeout(timerID);    
    goActive();
}
function stopTimer(e) {
    window.clearTimeout(timeoutID);
}
function goInactive() {
    idleSecondsCounter = 0;
    div.style.display = "block";
    div.innerHTML = "<strong>Inactivity detected.</strong> <p>Redirecting in <span id='countdown'>" + (idleTimeout - idleSecondsCounter) + " </span> seconds. <p>Please touch screen to cancel.";
    // show a count down here then redirect to google.com
    timerID = setInterval(function(){ 
        idleSecondsCounter++; 
        if(idleSecondsCounter >= 6) {
            clearTimeout(timerID);      
            window.location.href = "http://google.com";
        } 
        else {            
            document.getElementById("countdown").innerHTML = (idleTimeout - idleSecondsCounter);
        }
    }, 1000);    
}
function goActive() {
    div.style.display = "none";
    startTimer();
}

我在上面使用的时间是为了测试目的,在实际环境中会增加。

如有任何帮助,我们将不胜感激。

setup()执行时,页面加载时计时器无条件启动。

如果您只希望它在某个活动之后启动,只需从setup()代码中删除startTimer()即可——在任何将启动流程的活动中,您将调用resetTimer