Timothée Rebours Timothée Rebours - 1 year ago 106
Javascript Question

As of chrome 54, how dispatch a trusted textInput event from an extension?

I'm currently trying to trigger a trusted textInput TextEvent from a Chrome extension.

In Chrome ≤ 52 I could do the following thing:

const textEvent = document.createEvent('TextEvent')

In Chrome 53, I had the following workaround:

document.execCommand('insertText', false, 'myString')

But it shouldn't have worked at all (design mode not enabled, and should only work for

As expected, in Chrome 54 my workaround doesn't work anymore... Has anyone got an idea ?

It is related to this issue:
As of Chrome 53, how to add text as if a trusted textInput event was dispatched?

Answer Source

I confirm it does not work in Chrome 54 anymore. However, I have found a solution. I now use the clipboard API. To be more precise:

  • I create a temporary text area and focus it

  • I paste the current content of the clipboard to the text area, then save it to a variable

  • I then put the text I want to write in the text area, select it, and copy it

  • I put the focus back in the element I want to write to, and paste

  • I then reselect the text area, re-copy to put back the original stuff in the clipboard, and finally put the focus back in the element I'm writing to.

Some more trickery with the selection ranges goes on in my case, because I need to replace the selection text programatically, not only insert text, but I have explained all the main steps :) It's the only solution I have found that works everywhere, in ContentEditable divs and Inputs alike, with react or not. Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download