Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does dispatchEvent trigger `default` handler?

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?

like image 873
Martin Macak Avatar asked Sep 25 '22 07:09

Martin Macak


1 Answers

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.

like image 65
Ivo Dlouhy Avatar answered Nov 09 '22 02:11

Ivo Dlouhy