Insert text into textbox with add-on click (original) (raw)

December 12, 2025, 2:45am 1

I’m new to making Firefox plugins (and to JavaScript). I’ve been following the tutorials, but want to do something a little different. I’d like to insert a string of text into the focused element of a webpage when the user presses the extension button. E.g.:

So far, I’ve got a button that can do stuff when clicked just fine (tested it by getting it to do other stuff), but struggling to get text to be inserted into the focused element. This is my JS code:

function addText() {
    var textArea = document.activeElement; // Get the active element - might be where I'm going wrong?
    var start_position = textArea.selectionStart; // Start of the textArea's selection.
    var end_position = textArea.selectionEnd; // End of the textArea's selection

    var insertText = "Hello there!"; // Text to be inserted

    //Modify the textArea's text to include the custom text.
    textArea.value = `${textArea.value.substring(0,start_position)}
    ${insertText}
    ${textArea.value.substring(end_position,textArea.value.length)}`;
}

browser.browserAction.onClicked.addListener(addText); // Run the script when the button is clicked!

I suspect this is something to do with how I’m interacting with the activeElement, but wondering if there’s something wrong with my general plugin-writing too.

Thanks very much for any help!