I created this short snippet to test whether it's possible to trigger default
handler in JavaScript event.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script></script>
document.addEventListener('mousedown', function (e){
console.log('mousedown', e);
if (e.target === document.getElementById('target')) {
if (!e.__redispatched) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var ne = new MouseEvent('mousedown', e);
ne.__redispatched = true;
setTimeout(function (){
e.target.focus();
e.target.dispatchEvent(ne);
}, 1000);
}
}
}, true);
</head>
<body>
<input type="text" id="target"/>
<input type="text"/>
</body>
</html>
I expected that target
input would receive event and process it as normal, thus moving caret to the correct position (like it does normally on mousedown
). But nothing happens.
My question:
Am I doing something wrong with dispatchEvent
or do browsers ignore default handlers when processing synthetic events? Is there any material/proof to that?
Unfortunately browsers do ignore default event handlers for untrusted events.
See 3.4 Trusted events in the W3C UI Events Specification
Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.
Most untrusted events should not trigger default actions, with the exception of the click event. This event always triggers the default action, even if the isTrusted attribute is false (this behavior is retained for backward-compatibility). All other untrusted events must behave as if the Event.preventDefault() method had been called on that event.
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