检测用户何时离开网站

检测用户何时离开网站

本文介绍了检测用户何时离开网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建自己的网站访问库(为了好玩),就像Google Analytics一样,我可以检测用户何时访问我的网站,他们查看了哪些网页等。





我已经成功编码(在python中)用户第一次访问我的网站(使用cookie)&如何确定他们查看的页面。 但我不知道如何检测用户离开网站时的状态?

有没有JavaScript方法(也许我可以检测到页面/网址正在更改?)。我知道在HTTP中有一个引用标头,它告诉我用户来自哪里,也许当用户移动到另一个网站(我的外面)时,我可以得到这个通知(因为我将是该HTTP请求中的引用者) ?我是正确


解决方案

使用jQuery你可以触发这个:

  $(window).bind('beforeunload',function(){
// ajax调用或许
//触发写入数据库或文件系统...
});

纯JavaScript方式:

 < HTML> 
< head>
< script>
函数closeIt()
{
return这里的任何字符串值强制一个对话框到\\\
+
出现在关闭窗口之前。
}
window.onbeforeunload = closeIt;
< / script>
< / head>
< body>
< a href =http://www.somewhere.com>点击此处导航到
www.somewhere.com< / a>
< / body>
< / html>


I am trying to create my own website access library (for fun) like Google Analytics where I can detect when a user accesses my website, what pages they view etc.

Is there a way to determine when the user leaves a page &/or leaves the website for good?

I have successfully coded (in python) the detecting when the user 1st accesses my site (using a cookie) & how to determine what pages they view. But I don't know how I could detect when they user leaves the website for good?

Is there a way in javascript (maybe I can detect when the page/url is changing?). I know in HTTP there is a referrer header that tells me where the user came from, maybe when the user moves to another website (outside of mine), I can be notified of this (because I will be the referrer in that HTTP request)? Am I correct?

解决方案

Using jquery you can trigger this:

$(window).bind('beforeunload', function() {
    // ajax call perhaps
    // triggering a write to db or filesystem...
});

Pure javascript way:

<html>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" +
         "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.somewhere.com">Click here to navigate to
      www.somewhere.com</a>
</body>
</html>

这篇关于检测用户何时离开网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:32