How can I capture a click on a browser page without any effect on the reliability of the site?

My javascript code is being added to random sites. I would like to be able to report to my server when a (specific) link / button on a website is clicked. However, I want to do this without any interruptions in the site’s operation under any circumstances (such as an error in my code or my server ID, etc.). In other words, I want the site to perform the default action regardless of my code.

An easy way to do this is to add an event listener to the click event, call the server synchronously to make sure the call is registered, and then click. But I don’t want my site and code to make the click not fill.

Any other ideas on how to do this?

+3
source share
6 answers

Until you return false ; inside your callback and your AJAX is asynchronous . I do not think that you will have problems with your links that do not work.

$("a.track").mousedown(function(){ $.post("/tools/track.php") })

I also suggest that you encapsulate all this logic inside the try {} catch () block so that any errors that are not executed do not interfere with the normal normal operation of clicks.

+1
source

Perhaps something like this? I have not tested it, so it may contain some typo, but the idea is the same ...

<script type="text/javascript">
function mylinkwasclicked(id){
    try{
        //this function is called asynchronously
        setTimeOut('handlingfunctionname('+id+');',10);
    }catch(e){
        //on whatever error occured nothing was interrupted
    }
    //always return true to allow the execution of the link
    return true;
}
</script>

then your link might look like this:

<a id="linkidentifier" href="somelink.html" onclick="mylinkwasclicked(5)" >click me!</a>

or you can add onclick speaker:

<script type="text/javascript">
    var link = document.getElementById('linkidentifier');
    link.onclick=function(){mylinkwasclicked(5);};
</script>
+1
source

:

(new Image()).src = 'http://example.com/track?url=' + escape(this.href)
    + '&' + Math.random();
  • ( "-" )
  • - ( ajax)
  • Javascript

- .

+1

.

1) javascript , , , .

2) ajax , . , ajax, , , , click .

0

, , , URL- , .

0

, ping-

function link_clicked(el)
{
  try {
    var img = new Image();
    img.src = 'http://you?url=' + escape(el.href) + '&rand=' + math.random();
    window.onbeforeunload = wait;
  }catch(e){}
  return true;
}

function wait()
{
  for (var a=0; a<100000000; a++){}
  // do not return anything or a message window will appear
}

, , , . wait() , , . , , . , , , - , . , , .

-1

Source: https://habr.com/ru/post/1708546/


All Articles