Simulate Keyboard Input in web extension with Javascript

Viewed 52

is there a way to simulate a raw Keyboard input in javascript, so that it is possible to f.e. fill in text on your webpage via a web extension?

My plan is, to load in a web extension (firefox) that f.e. writes a word into the searchbar of youtube.

All that I could find is the Keyboard events eg:

var e = new KeyboardEvent('keydown',{'keyCode':32,'which':32});
document.dispatchEvent(e);

Sadly this only triggers a keydown event, so that I can start and stop videos but cant type into the search bar text field.

Any help is really appriciated!

Thanks in advance.

1 Answers

There are a couple of ways we can do this,

One of the easiest ways is to select the search DOM element, set the value of the search element, and then dispatch a click event on the search button.

document.querySelector('input').value = "Hello world";
document.querySelector('button#search-icon-legacy').click();

If you want to do it the way you mentioned, youtube supports a keyboard shortcut to access the search input. By pressing the '\' key you can get the focus on the search input. So you can access the search box using KeyboardEvent by dispatching a 'keydown' event to '\' (191).

The code looks something like this,

const slash = new KeyboardEvent('keydown', {'keyCode':191, 'which':191})
const k = new KeyboardEvent('keydown', {'keyCode':75, 'which':75})
const enter = new KeyboardEvent('keydown', {'keyCode':13, 'which':13})

document.dispatchEvent(slash)
document.dispatchEvent(k)
document.dispatchEvent(enter)
Related