Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect jQuery function from outside access

I'm using jQuery in an app which registers user clicks to perform a given action through the .click() binding, and I want this functionality to be available only through a user mousedown. One of my friends pointed out today that it's possible to run $(element).click() from a javascript terminal in Firebug (or something similar), and achieve the same functionality as clicking on the element -- something I'd like to prevent. Any ideas on how to go about doing this? Thanks for your input.

like image 336
man1 Avatar asked Jul 23 '10 06:07

man1


2 Answers

Short answer: No, you can't really prevent it.

Long answer: Any event like a click event is bound to such called Event handlers. Those handlers are functions which are executed when a given event occurs. So if you click on an element, your browser checks if any event handlers are bound to it, if so it fires them. If not, the browser will try to bubble up the event to the parent elements, again checks if there are any event handlers bound for that kind of event .. and so forth.

jQuerys .trigger() method (which is what you actually call if calling .click() for instance) just does the same thing. It calls the event handlers which are bound to a specific element, for a specific event.

EDIT

There might some simple ways to somekind of soft detect a real click, for instance you might check for the toElement property within an event object. That property is not set when triggered. But then again, you can easily fake that aswell with .trigger(). Example:

$(document).ready(function() {
  $('#invalid2').bind('click', function(e){
      alert('click\nevent.target: ' + e.toElement.id);
      console.log(e);
  });

  $('#invalid1').bind('click', function(){
      $('#invalid2').trigger({
          type: 'click',
          toElement: {id: 'Fake'}
      });
  });
});​

Working example: http://www.jsfiddle.net/v4wkv/1/

If you would just call $('#invalid2').trigger('click') the toElement property would not be there and therefore fail. But as you can see, you can add like anything into the event object.

like image 153
jAndy Avatar answered Sep 23 '22 23:09

jAndy


What are you trying to prevent? Someone messing with your client side script? You can do things like obfuscate your code but not much other than that. But even doing this is just making it more hassle than it's worth in my opinion.

If you don't want people doing certain things move the functionality to the server.

Sorry to be bearer of bad news.

like image 41
spinon Avatar answered Sep 24 '22 23:09

spinon