Is there any way to programmatically trigger keyboard shortcuts from Javascript? For example, take gmail.com, where pressing 'e' will archive the selected email.
Could I write any type of code (say in a Chrome Extension) that can simulate the user pressing 'e' on the keyboard?
E.g. I tried copy-pasting something like this in the Chrome console:
document.body.addEventListener('keydown', function(event) {
console.log('key detected: ', event);
});
document.body.addEventListener('click', () => {
console.log('click...');
document.body.dispatchEvent(new KeyboardEvent('keydown', {
'key': 'e',
'keyCode': 69,
'which': 69,
'code': 'KeyE',
'isTrusted': true, // this has no effect
'bubbles': true,
'cancelable': true,
'view': window,
'charCode': 0,
}));
});
So any click on the page will print the key, which looks the same as pressing 'e' on the keyboard. But the click event keypress does not trigger the 'archive' feature in Gmail.
Is it that the event is not trusted, and it's not possible to do what I had intended?