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

十年热恋 提交于 2019-12-24 16:41:59

问题


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


回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/10563284/is-it-possible-to-track-visitor-that-leave-or-page-to-another-sites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!