烦人的弹出窗口 - (或其他更优雅的解决方案)

时间:2010-12-07 20:42:13

标签: javascript ajax

这是我的“需要” - 我有一个用户打开一个显示文档的窗口,我需要记录用户将该窗口“聚焦”或“打开”的时间量...如果用户查看另一个窗口,我想停止记录时间 - 如果他们重新关注该页面,则继续记录...基本上我想“知道”用户阅读页面需要多长时间。

这是一种审核类型方案,其中用户是需要记录时间的“可信”成员...我想保留“运行总计”仅供参考 - 所以如果用户说花了10分钟,在页面上,但我的日志显示窗口只打开了2分钟,我知道我遇到了问题......无论是我的代码还是我的人......;)

我的想法是当页面处于焦点时停止js计数器,暂停模糊或关闭,并将数据Ajax返回到我的数据库......如果用户返回,则将任何后续时间添加到该记录。 ..

onUnload似乎不起作用,至少在我尝试的时候 - 加上它没有关闭浏览器...所以我想我可以在文档窗口关闭时启动一个新窗口(不是令人讨厌 - 但是要对服务器进行日志记录调用,然后关闭它自己)。

有人有解决方案吗?我知道这一切都是“糟糕”的设计,但如果某人有'正确'的方式来处理这种情况 - 请告诉我。 (BTW-IE是一项要求 - 它是基于内联网的IE7要求。) THX

========下面的示例代码 - 这是'不'正在工作......有点============ 当我说它不工作时,这就是我的意思......“XMLHttpRequest”正在制作中,我假设因为响应是我期望的消息 - 但是日志不是变化(我知道你会说它是php页面,但如果我直接调用url - 它工作正常......所以它不是日志页面,另外60秒setInterval()似乎随机触发,因为我的响应警报刚刚弹出,有时10 in in没有时间的一排,肯定不是在'常规'60秒间隔...那么?

<script type="text/javascript">

var closeMe = 0;
var logMe = 0;

//the window doesn't have focus, do nothing or something that let's them know we're not logging at the moment
function onBlur() {
    //after 2 min of non focus, close it.
    closeMe = setInterval('window.close()',120000); //after 2 min of non focus, close it.
};

//the window has focus... keep logging.
function onFocus(){
    //stop the close counter - in the event to 'blurred' sometime
    clearInterval ( closeMe );  
    //run the AJAX on a schedule - we're doing it every minute - bu tyou can do it as often as you like
    logMe = setInterval('logTime()',60000);
};

//call a script that logs another minute...
function logTime() {
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "ajax-on-time-interval.php", false);
    xhReq.send(null);
    var serverResponse = xhReq.responseText;
    alert(serverResponse); 
}

// check for Internet Explorer... IE uses 'onfocusin/out" - everything else uses "onfocus/blur"
if (/*@cc_on!@*/false) {
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

</script>

3 个答案:

答案 0 :(得分:3)

我一直认为基于Ajax的常规“心跳”会每隔n秒更新一次底层数据库数据(取决于您需要的粒度,我认为每分钟都足够了)将是一个整洁的解决方案而不是弹出窗口,也避免了并非所有浏览器都优雅地处理onunload等事实。

那就是说,我假设这些机器上会启用JavaScript。 (根据你的问题看似公平。)

答案 1 :(得分:1)

window.onfocus和onblur记录在MDC中,但它们不是标准。显然,IE有document.onfocusin和.onfocusout:

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

我没试过。我刚才在这里读到它。 http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

答案 2 :(得分:0)

部分解决浏览器关闭/崩溃问题的一个有点草率的解决方案是使用ajax函数在文档处于焦点时以设定的间隔对服务器DB进行ping操作。这样,如果客户端崩溃,您将在30秒内准确了解文档的打开时间。

相关问题