Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
RicardO Avatar asked Aug 23 '11 14:08

RicardO


People also ask

How can I find out if someone is leaving a website?

The most reliable way to detect when a user leaves a web page is to use visiblitychange event. This event will fire to even the slightest changes like changing tabs, minimizing the browser, switching from browser to another app on mobile, etc.

Which event triggers when the user leaves the page?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

Which of the following body tag handler is triggered when a visitor is about to leave the page?

The Onunload event handler in Javascript is an event handler that is triggered when a user leaves the current web page.


2 Answers

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
    }
}
like image 200
Jeremy Avatar answered Nov 02 '22 12:11

Jeremy


I've got one idea, but I don't know if it's work. My suggestion is, add each link an onClick event with a function call. That function reads just the href attribute and store into a variable with global scope.

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

The html for the a tags must be looks like following:

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

and in your given function:

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

It is just an idea, but I think it is worth to try it.

like image 24
Reporter Avatar answered Nov 02 '22 12:11

Reporter