Search code examples
javascriptgoogle-chrome-extension

How can I enter data into a custom-handled input field?


My extension has a context menu with items. What I'd like it to do: is when I right-click a editable HTML element (e.g. input or textarea) and then select and click on an item in my menu - some value defined by my extension gets entered into the input.

For now I have realised that:

document.activeElement.value = myValue

works alright with simple inputs.

Problems start when there is an input with custom onChange event handling, e.g. a calendar or a phone input, or currency input - that transforms user-input in some way.

Since I am setting a value directly onto the element - the handling logic gets omitted, which causes all manner of problems.

Since JavaScript doesn't allow for KeySend-like features - what are my options here?

I have thought about testing tools like Puppeteer or Cypress - but they all seem not to be packageable into an extension. Puppeteer does have such an option, but it still requires a node instance running to connect to. And I would like my extension to be solely client-sided and distributed in Chrome webstore - so I cannot ask my users to spin up a node server.


Solution

  • There is a built-in DOM method document.execCommand.
    In case of an extension, use this code in the content script.

    // some.selector may be `input` or `[contenteditable]` for richly formatted inputs
    const el = document.querySelector('some.selector');
    el.focus();
    document.execCommand('insertText', false, 'new text');
    el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
    

    It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput, input) with isTrusted field set to true. On some pages the change event should be additionally dispatched as shown above.

    You may want to select the current text to replace it entirely instead of appending:

    replaceValue('some.selector', 'new text');
    
    function replaceValue(selector, value) {
      const el = document.querySelector(selector);
      if (el) {
        el.focus();
        document.execCommand('selectAll');
        if (!document.execCommand('insertText', false, value)) {
          // Fallback for Firefox: just replace the value
          el.value = 'new text';
        }
        el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
      }
      return el;
    }
    

    Note that despite execCommand being marked as obsolete in 2020, it'll work in the foreseeable future because a new editing API specification is not finished yet, and knowing how slow such things usually move it may take another 5-20 years.