1

I'm working on a Firefox extension that inserts Polish characters to any text field using keyboard shortcuts. It's working for all text fields, except for Facebook, Draft.js, and any React contentEditable DIV.

Steps to reproduce:

  1. Load http://facebook.github.io/draft-js/
  2. Open Chrome Dev Tools
  3. Select the Draft.js input box so that the input caret is present
  4. execute document.execCommand("insertHTML", false, "X"); in the dev tools console

Result expected: X is added to the input box

Actual result: X is added to the input box twice. You're able to delete one of the instances, but the other one is undeletable but is selectable.

Note: Once at least one character has been typed into the Draft.js input the command works as expected.

Gregory R.
  • 1,815
  • 1
  • 20
  • 32

1 Answers1

1

I figured it out. Before you execute document.execCommand("insertHTML", false, "X");, check to see if the length of <span data-text="true"></span> is 0. If it is, just run document.execCommand("undo", false); following the insertHTML execCommand, and Voila! it works!

Here's the code:

if (document.querySelectorAll('span[data-text="true"]').length === 0) {
    document.execCommand("insertHTML", false, "X");
    document.execCommand("undo", false);
} else {
    document.execCommand("insertHTML", false, "X");
}

It will check to see if you have entered the first character. If you did, it'll do the undo execCommand and remove the extra X. The else will just insertHTML since it won't insert any extras once characters have been entered.

Gregory R.
  • 1,815
  • 1
  • 20
  • 32
  • Hi, does this still work for you? I'm getting a "could not display composer" error when I execute `execCommand()` on facebook and an error in the console when I execute it on https://draftjs.org/. – JoniVR Jan 18 '19 at 20:50
  • I am not sure because I haven't updated my Firefox extension for a while and it has been removed from the Mozilla add-ons page. I will need to update it when I have a chance, and I will let you know. – Gregory R. Jan 18 '19 at 20:59
  • Thank you very much! I'm trying to get it to work with draftjs but it just keeps throwing that error, I made a question about it here: https://stackoverflow.com/questions/54256517/make-document-execcommandinserttext-false-message-work-with-draftjs If you do manage to get it working, perhaps you could post the answer there so I can give you credit for it. – JoniVR Jan 18 '19 at 21:01