gpt4 book ai didi

JavaScript 定时重定向

转载 作者:行者123 更新时间:2023-12-02 15:21:10 27 4
gpt4 key购买 nike

我已经设置了基于重定向的用户是否在页面上处于事件状态。感谢this tutorial我已经完成了 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 将启动该过程。

关于JavaScript 定时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34043423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com