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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With