我如何检测用户何时离开我的网站,而不仅仅是去到另一个页面

How can I detect when the user is leaving my site, not just going to a different page?

本文关键字:不仅仅是 网站 另一个 我的 离开 何检测 检测 何时 用户      更新时间:2023-09-26

我有一个onbeforeunload处理程序

window.onbeforeunload = unloadMess;
function unloadMess(){
  var conf = confirm("Wait! Before you go, please share your stories or experiences on the message forum.");
    if(conf){
    window.location.href = "http://www.domain.com/message-forum";
    }
}

但是我不确定如何知道他们点击的url是否在网站内。

我只是想提醒他们,如果他们要离开网站。

这是不可能做到100%可靠的,但如果你检测到用户点击了页面上的链接,你可以使用它作为一个基本正确的信号。像这样:

window.localLinkClicked = false;
$("a").live("click", function() {
    var url = $(this).attr("href");
    // check if the link is relative or to your domain
    if (! /^https?:'/'/./.test(url) || /https?:'/'/yourdomain'.com/.test(url)) {
        window.localLinkClicked = true;
    }
});
window.onbeforeunload = function() {
    if (window.localLinkClicked) {
        // do stuff
    } else {
        // don't
    }
}

我有一个想法,但我不知道它是否工作。我的建议是,为每个链接添加一个带有函数调用的onClick事件。该函数只读取href属性并将其存储到具有全局作用域的变量中。

var clickedHrefAttrValue = "";
function getClickUrl(currentLink)
{
   clickedHrefAttrValue = $(currentLink).attr("href");
   return true;
}

a标签的html必须如下所示:

<a href="<url>" onClick="getClickUrl(this)">Linktext</a>

和给定函数中的

function getClickUrl()
{
   if (clickedHrefAttrValue.indexOf("<your condition>" > -1)
   {
     //what ever you want do to
   }
}

这只是一个想法,但我认为值得一试。

如果你有问题,因为你的网站可能有绝对和相对的本地链接,我有另一个解决方案(使用jQuery):

演示
/* EXTERNAL LINK WARNING
=========================================*/
$('a').on('click', function(e){
    e.preventDefault();
    var url = $(this).attr('href'),
        host = location.host;       
    if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){
        /* If we find the host name within the URL,
               OR if we do not find http or https, 
               meaning it is a relative internal link
            */
        window.location.href = url;
    } else {
        var warn = confirm('You''re leaving the domain.'n'nAre you sure?');
        if(warn == true) {
            window.location.href = url,'_blank';
        } else {
            e.preventDefault;
        }
    }
});

所以我需要这样做,这样如果用户从任何页面离开网站,我就可以注销用户,但如果他们在网站内导航,则不行。以下是我使用JS和PHP的解决方案

在他们需要保持登录的每个页面上,设置一个会话变量:

<?php
    session_start();
    $_SESSION["isInSession"] = true;
?>
现在创建两个脚本:

clear-in-session.php

<?php
    session_start();
    unset($_SESSION["isInSession"]);
?>

logout.php

<?php
    session_start();
    if(isset($_SESSION["isInSession"]) exit();
    //do logout code here
?>

现在我们在JS中设置两个事件:

window.addEventListener('beforeunload', function(event) {
    $.ajax({
        type: 'POST',
        async: false,
        url: 'clear-in-session.php'
    });
});
window.addEventListener('unload', function(event) {
    $.ajax({
        type: 'POST',
        async: false,
        url: 'logout.php'
    });
});

当用户导航到同一站点的另一个页面时,解释事件的顺序:

  1. 用户导航离开
  2. beforeunload被触发,调用clear-in-session.php删除isInSession变量
  3. 加载新页面,将isInSession设置为true
  4. unload被触发,调用logout.php,但是因为isInSession被设置为true,注销代码永远不会被调用

当用户导航到站点外的页面时(或站点上没有设置isInSession的任何页面):

  1. 用户导航离开
  2. beforeunload被触发,调用clear-in-session.php删除isInSession变量
  3. 新页面已加载
  4. unload被触发,调用logout.phpisInSession已被删除,因此注销代码调用

抱歉necro,但这个线程仍然出现在搜索这个问题的答案

注意:这个答案使用jQuery来post调用php。在纯JS中完全可以做到这一点,但是用jQuery

更容易说明这一点。

我最近在我的网站上实现了一个很好的解决方案。想象一下,你网站上导航用户的所有东西要么是链接(锚标签),要么是按钮,要么是可点击的图像,或者是这些线上的东西。它肯定不是body元素。

现在,当用户离开网站时,他/她可以输入url并按回车键,点击书签或按后退/前进按钮。

当用户这样做时,执行以下操作:

$(window).on('beforeunload', function(e)){
    if(e.target.activeElement.nodeName.toLowerCase() == 'body'){
       yourFunction();
});

在这些情况下(当用户离开网站时),正文会成为目标中的活动元素,而当用户点击网站内部可导航元素时,情况就不是这样了。

这是一个干净、简单的解决方案。如果你有任何问题,请告诉我。