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

gfi*_*ost 12 javascript jquery

我有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";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 18

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常好的且不引人注目的解决方案 (2认同)