2 分钟后重定向页面,即使 window 未激活

Redirect page after 2 minutes, even if window is not active

我正尝试在 [2] 分钟后重定向页面,即使该页面未处于活动状态。这主要针对移动用户,他们可能会离开页面,导致倒计时停止。

当移动用户登陆页面时,会显示一条消息,内容将在 2 分钟内准备就绪。大多数人不会等待并关闭 window,只会等待 return 2 分钟。稍后,仍然需要等待整个 2 分钟...

我目前正在使用以下代码,但它似乎不起作用

<script>
    var timer = setTimeout(function() {
        window.location='http://example.com'
    }, 120000);
</script>

非常感谢! 克里斯

您不能在两分钟后重定向。但是,如果用户在至少两分钟后将其返回到前台,您可以重定向:

var before=(new Date()).getMinutes();
setInterval(function() {
  if((new Date()).getMinutes()-before >= 2){
    window.location='http://example.com';
  }
}, 1000);//compare each second

如果您希望它在页面关闭时也能正常工作,您可以将它存储在 localStorage 中:

 localStorage.setItem("before",localStorage.getItem("before") || (new Date()).getMinutes());
setInterval(function() {
  if((new Date()).getMinutes()-localStorage.getItem("before") >= 2){
    window.location='http://example.com';
  }
}, 1000);//compare each second

请注意,这不会在整点变化时起作用,因此您可以重新编码,使其基于 getTime() ,但这取决于您...

检查用户代理是否在移动端。然后,设置 Timeout 在 2 minutes.then 之后触发函数,重定向到你想要的 URL.

function detectmob() { 
 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    return true;
  }
 else {
    return false;
  }
}

if(detectmob()){
setTimeout(function() {
    window.location = "http://example.com";
  }, 120000);
  

}

您可以使用 <meta> 标签执行此操作:

<meta http-equiv="refresh" content="120; URL=http://example.com">

我没有在这里进行详尽的测试,但这似乎适用于最新的 Chrome、EDGE 和 FireFox 浏览器,即使页面未处于焦点。