【发布时间】:2015-12-02 13:00:38
【问题描述】:
我已经设置了一个基于重定向的重定向,无论用户是否在页面上处于活动状态。感谢this tutorial 我有 99% 的工作。我只有一个功能。
JS 是 google chrome 扩展的一部分。
页面上的 2 秒不活动后会弹出重定向警告,如果 5 秒内没有其他活动 - 页面将重定向到 google.com(使用 google.com 仅用于测试目的)。
一旦重定向到 google.com,计时器会在 2 秒后再次启动 - 我不希望这样。
我只希望当用户在 google.com 上活动(即触摸屏幕)时启动计时器。
我需要在某处添加一个额外的 stopTimer 函数吗?
我基本上希望计时器出现在除主页之外的每个页面上(在本例中为 google.com)。
到目前为止我的代码 - 我创建了一个 JS Fiddle;
google 重定向在 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();
}
我上面使用的时间是为了测试目的,在实际环境中会增加。
任何帮助将不胜感激。
【问题讨论】:
-
你知道页面重定向时内容脚本会重新加载到新的 URL 上吗?
-
谢谢@wOxxOm - 那么这对我的代码或下面提供的答案有何影响?
-
将此信息与答案结合起来,您会看到
setup()在重定向后无条件执行。
标签: javascript function redirect google-chrome-extension timer