javascript – 如何检测用户何时离开我的网站,而不只是到不同的页面?

前端之家收集整理的这篇文章主要介绍了javascript – 如何检测用户何时离开我的网站,而不只是到不同的页面?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个处理程序forbeforeunload
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";
    }
}

但我不知道如何知道他们点击页面上的网址是否在网站内.

我只是希望他们提醒他们是否离开网站.

解决方法

这不可能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
    }
}
原文链接:https://www.f2er.com/js/151832.html

猜你在找的JavaScript相关文章