Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture a click on the browser page without any possible effect on the site's robustness?

Tags:

javascript

My javascript code is added to random websites. I would like to be able to report to my server when a (specific) link/button on the a website is clicked. However I want to do it without any possible interruption to the website execution under any circumstances (such as error in my code, or my server id down etc.). In other words I want the site to do its default action regardless of my code.

The simple way to do it is adding event listener to the click event, calling the server synchronously to make sure the call is registered and then to execute the click. But I don't want my site and code to be able to cause the click not to complete.

Any other ideas on how to do that?

like image 485
Nir Avatar asked Dec 01 '25 05:12

Nir


2 Answers

As long as you don't return false; inside your callback and your AJAX is asynchronous I don't think you'll have any problems with your links not working.

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

I would also suggest you encapsulating this whole logyc inside a try{} catch() block so that any errors encauntered will not prevent the normal click behaviour to continue.

like image 200
duckyflip Avatar answered Dec 03 '25 18:12

duckyflip


Perhaps something like this? I haven't tested it so it may contain some typo's 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 could look like this:

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

or you could add the onclick dynamically:

<script type="text/javascript">
    var link = document.getElementById('linkidentifier');
    link.onclick=function(){mylinkwasclicked(5);};
</script>
like image 22
Peter Avatar answered Dec 03 '25 19:12

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!