1

Given a button reference, you can use javascript on your console to .click() it.

Is there a way for my website to differentiate between a click triggered by a mouse and a click triggered by the user's javascript? Or are these effectively equivalent from the browser's point of view?

Saturn
  • 17,888
  • 49
  • 145
  • 271
  • [The HTMLElement.click() method simulates a mouse click on an element.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click) – Simone Rossaini Mar 31 '22 at 08:12
  • @SimoneRossaini yeah, that's what I want to differentiate from if at all possible. – Saturn Mar 31 '22 at 08:12
  • Obviously not :) If it simulates the mouse click it does it 100% – Simone Rossaini Mar 31 '22 at 08:13
  • 2
    You cannot differentiate in the click handler itself. But you **can** check for mouse position movement beforehand. JavaScript typically doesn't move the mouse pointer. – Peter Krebs Mar 31 '22 at 08:16
  • 1
    Does this answer your question? [Detect if button click real user or triggered by a script](https://stackoverflow.com/questions/14794380/detect-if-button-click-real-user-or-triggered-by-a-script) – Simone Rossaini Mar 31 '22 at 08:20
  • In which case / element you will recognise if the user is clicked by mouse or press enter? – Maik Lowrey Mar 31 '22 at 08:27

1 Answers1

2

Use Event.isTrusted

Yes, you can use the event.isTrusted property. Will be true when the user clicks as shown in this code snippet.

mybutton.addEventListener("click", function(e) {
    console.log( "isTrusted = " + e.isTrusted );
});

test.addEventListener("click", function(e) {

  mybutton.click();

});
<button id="mybutton">My Button</button>

<button id="test">Test</button>
Yogi
  • 6,241
  • 3
  • 24
  • 30
  • Might be noted that click events fired from other means than a mouse will also have it set to true (e.g if you press the Enter key of your keyboard while focusing the button). Also, this property is [[LegacyUnforgeable\]](https://webidl.spec.whatwg.org/#LegacyUnforgeable), so it can't be tampered by code. – Kaiido Mar 31 '22 at 09:01