5

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')
textEvent.initTextEvent('textInput',
            true,
            true,
            null,
            'myString');
document.activeElement.dispatchEvent(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 contenteditable divs)

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?

  • `insertText` workaround in the linked answer for Chrome 53 [works for me](https://jsfiddle.net/2nfhrj1j/22/) in Chrome 54 and 56 too. Design mode flag isn't checked in the [source code](https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/dom/Document.h?sq=package:chromium&dr=CSs&rcl=1476847656&l=906). – wOxxOm Oct 19 '16 at 19:56

1 Answers1

3

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!

arantes
  • 126
  • 4