Search code examples
javascriptreactjsdomdom-events

Is it possible to automatically write text in a React lexical editor using a Chrome extension?


Im trying to write a chrome extension that automatically writes text in the text box when a user presses a button. Im pretty sure the website I am trying to make the chrome extension work on is using a lexical editor and react.

Does anyone know how I can input text into a lexical editor from its DOM element?

Ive tried sending Keypress events to the lexical editor element and changing its inner text without any luck.


Solution

  • To simulate user input in the editor, we can use InputEvent API to dispatch the appropriate events.

    const lexicalEditor = document.querySelector('editor-selector');
    
    const inputEvent = new InputEvent('input', {
      data: 'Your text here',
      inputType: 'insertText',
      dataTransfer: null,
      isComposing: false,
      bubbles: true,
    });
    lexicalEditor.dispatchEvent(inputEvent);
    

    Tested on Facebook (automated facebook post through chrome extension)