Event.isTrusted property from UI Events shipped in Chrome 46

Working on a large JavaScript project is not easy. We need fine tuning in everything we do, and sometimes we need to distinguish between a user-generated event and an event generated by a script.
Why is this important? Because the ability to distinguish between a user initialized action and a scripted one can make the difference to optimize the UI.

In our scenario we have a toolbar which should be shown if the user performs an action, specifically selects some text. The same action can be triggered by a script as a consequence of a correction or a modification in the DOM. Distinguish between the two can be quite tricky and error-prone, surely not bug-free.

In Chrome 46 as well as in Firefox we have available a flag: event.isTrusted. This flag gives us a whole lot and allows to clean a lot of code.
The usage is quite simple:

The HTML:

<button type="button" id="button">First Button</button>
<button type="button" id="secondbutton">Second Button</button>
<div id="console"></div>

The JavaScript:


var button = document.querySelector('#button');
var secondButton = document.querySelector('#secondbutton');
var console = document.querySelector('#console');
button.addEventListener('click', function (e) {
  var text = e.isTrusted ? 'is trusted ' : 'is not trusted ';
  var block = document.createTextNode(text + ';');
  console.appendChild(block);
}, false);

secondButton.addEventListener('click', function (e) {
	button.click();
}, false);

Demo:

More info on W3C