Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate keys entered in an input web element in Chrome 56 with pure JavaScript?

I am developing some programmatic automation within a web page and am attempting to enter a keystroke into an input web element in Chrome 56 (specifically 56.0.2924.87) and cannot seem to get it working.

I have done my homework and attempted MANY online examples including the ones found here: Javascript - simulate key events on Chrome 53, but with no luck.

This is my most recent (currently non-working) attempt based on the solution provided in the question above:

<!DOCTYPE html>

<head>
  <meta charset="utf-8" />
  <title>Keyboard Events</title>
</head>

<body>
  <input id="id_input" onkeydown="console.log(event);">
  <button onclick="
    var e = new Event('keydown');
    e.keyCode = 65;
    document.getElementById('id_input').dispatchEvent(e);
    ">click me</button>
</body>

</html>

You can observe the event being generated, but no character appears in the input web element.

I would greatly appreciate a working JavaScript only example, working in Chrome 56, of pressing a button on a page and a character appearing in the input web element WITHOUT setting the "value" property of the input web element. The working solution must be causing characters to appear only by using events (presumably keypress/keydown, etc.)

UPDATE: My issue is different than this issue: How to trigger event in JavaScript? because I'm already using the dispatchEvent method listed in the solution. The answer to my question will likely include an additional step not already outlined in the multiple attempts from the first link I included.

like image 766
Loren Avatar asked Mar 07 '17 00:03

Loren


People also ask

Can you simulate a keypress in JavaScript?

We use event handlers to simulate keypress events in JavaScript.

How do you press Enter key programmatically in typescript?

You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.

How do you press a key in JavaScript?

To record a keypress event in JavaScript, use the code below: // Add event listener on keypress document. addEventListener('keypress', (event) => { var name = event. key; var code = event.


1 Answers

In terms of implementing this functionality from within in a Chrome extension, it looks like it is possible with workarounds. These links might be able to help.

Keydown Which Not Working Chrome Extension
How to to initialize keyboard event with given char/keycode in a Chrome extension?

On a webpage however, this is not possible. At least not with Chrome 56. There is an isTrusted read only attribute of the Event object.

The event is "trusted" if invoked by a real user on a keyboard, and is "not trusted" if invoked by a script.

As indicated here, untrusted events do not invoke the default action. This has been present since Chrome 53.

like image 126
grizzthedj Avatar answered Nov 15 '22 09:11

grizzthedj