如何检测用户何时离开我的网站,而不仅仅是去另一个页面? [英] How can I detect when the user is leaving my site, not just going to a different page?

查看:102
本文介绍了如何检测用户何时离开我的网站,而不仅仅是去另一个页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有onbeforeunload的处理程序

I have a handler for 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";
    }
}

但我不知道如何知道他们点击页面的网址在网站内。

but I'm not sure how to know if the url they clicked on the page is within the site.

我只是希望他们在离开网站时提醒他们。

I just want them to alert them if they will leave the site.

推荐答案

不可能100%可靠地执行此操作,但如果您检测到用户点击了页面上的链接,您可以将其用作大部分正确的信号。这样的事情:

It's not possible to do this 100% reliably, but if you detect when the user has clicked on a link on your page, you could use that as a mostly-correct signal. Something like this:

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
    }
}

这篇关于如何检测用户何时离开我的网站,而不仅仅是去另一个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆