bijakas2
bijakas2

Reputation: 33

Is it possible to track visitor that leave or page to another sites?

Is it possible to track visitor that leave or page to another sites, like ask question only when they want move to another sites or other domain name? I write this code

<script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "leave?";
  }
</script>

But this code work everytime even on my own pages. I want to make this code to run just if visitors go to another domain by tiping URL (Not by links). Is it possible? Thanks

Upvotes: 1

Views: 688

Answers (3)

Joseph
Joseph

Reputation: 119857

I think this is a task for a browser plugin, not a page script. It's not possible for JS to know what the user does outside the page.

If this were possible, that would be a whole new security problem, a privacy issue, and I won't visit your site.

Upvotes: 2

ChristopheCVB
ChristopheCVB

Reputation: 7315

I've tried a thing here, not sure it works on every cases...

window.onbeforeunload = confirmExit;

function confirmExit(event)
{
    console.log(event);
    console.log("Current : " + event.srcElement.domain);
    console.log("Target : " + event.target.domain);
    if (event.srcElement.domain != event.target.domain)
    {
        return "leave ?";
    }
    else
    {
        // staying here
    }
}​

Upvotes: 0

Imdad
Imdad

Reputation: 6042

As you have tagged jquery in this question I guess you are already using http://jquery.com/

<script language="JavaScript">
  $(document).ready(function(){
       $("a").click(function(){
       if( fnGetDomain(document.location) == fnGetDomain($(this).attr("href")) )
       {
            return true;
       }
       else{
            return confirm("Leave page?");
       }

   });
});
function fnGetDomain(url) {
  return url.match(/:\/\/(.[^/]+)/)[1];
}
</script>

You can use document.location.href in place of document.location if there is any problem

Upvotes: 0

Related Questions