Search code examples
javascriptgoogle-chrome-extensiontextfield

Chrome extension how to enter text in any selected text field


I am making a Chrome extension that generates nicknames when you press Ctrl+Shift+U, and it should automatically enter the generated name in the selected text field, if one is selected. My problem is that there are many types of text fields, the most basic being input. This is currently my function that generates the nickname, which works for input fields and textarea fields, but for nothing else.

//Nickname gets generated here
//...

var inp = document.querySelectorAll("input");
var txt = document.querySelectorAll("textarea");
    
for (var i=0;i<inp.length;i++) {
    if (inp[i] == document.activeElement) {
        inp[i].value = nick;
    }
}
    
for (var i=0;i<txt.length;i++) {
    console.log(txt[i]);
    if (txt[i] == document.activeElement) {
        txt[i].innerHTML = nick;
    }
}

Basically, what I think I would need, is some kind of function that can act like the user is typing the name, without directly changing the value of a field.


Solution

  • Thanks to the answer of wOxxOm, with a bit of modification, I got it to work. This is my final code:

    //Nickname gets generated here
    //...
    
    const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:'', code:'', location:0};
    const element = document.activeElement;
    
    if (element) {
    
        element.dispatchEvent(new KeyboardEvent("keydown", keyboardEventInit));
        element.value = nick;
        element.dispatchEvent(new KeyboardEvent("keyup", keyboardEventInit));
        element.dispatchEvent(new Event('change', {bubbles: true}));
    
    }