区分Meta Refresh和其他刷新或页面卸载事件

时间:2014-05-17 04:53:47

标签: javascript jquery html

我的情况是,如果用户在页面中停留X秒,我会将用户重定向到另一个页面。

我正在使用Meta Refresh标签。

<meta http-equiv="refresh" content="600; URL={{redirectURL}}">

此外,我想向用户显示本机窗口,如果他在X秒之前尝试刷新或离开页面,而不是在页面中提交表单。

我使用以下脚本来显示本机窗口。

<script type="text/javascript">
$(function(){
var submitted = false;
$(".cancel_submit").on('click',null,function (e){
submitted=true;
});

window.onbeforeunload = function()
{
if(!submitted && gbl_time>15)
{
str = "This is a secure page. Leaving this page will end your current session. Are you sure you want to leave?.";
return str;
}
submitted=false;
}

});

但本机也显示为元刷新?我怎样才能避免它?

1 个答案:

答案 0 :(得分:1)

顺便说一下:你的元刷新是在600秒后调用的吗?

你的问题: 元刷新会激活window.onbeforeunload-event,因为加载URL是当前webseite的卸载。不幸的是,window.onbeforeunload-event没有给你一个提示,确切发生了什么事件。

使用Javascript函数设置重定向而不是元刷新:

var callfromwait = false;

window.onbeforeunload = function() {
   if(!callfromwait){
     return "Sure, you want to leave our website?";   
   }
};

window.setTimeout(function(){
 callfromwait= true;
 window.location.href = "http://www.test.de";
}, 5000); // milliseconds

演示:http://jsfiddle.net/65wsm/