make document.execCommand('insertText', false, 'message') work with draftjs?

前端 未结 1 1076
粉色の甜心
粉色の甜心 2021-01-19 01:08

I\'m working on an application which needs to insert text into a contenteditable=\"true\" div (a Draftjs based textfield to be precise).

No

相关标签:
1条回答
  • 2021-01-19 02:06

    Although the question was asked a long ago and @JoniVR found a workaround, this may help someone else.

    I was also having a similar problem while working on an extension. I also tried the method document.execCommand('insertText', false, text). It worked on LinkedIn but not on Facebook. It was inserting text in the wrong node. Although document.execCommand API works in some places, it's obsolete now.

    For Facebook and any other sites using drafjs editor, We need to dispatch a paste event using dataTransfer and clipBoardEvent APIs to make draftjs think that the text is pasted and process accordingly.

    const dataTransfer = new DataTransfer();
    
    function dispatchPaste(target, text) {
      // this may be 'text/html' if it's required
      dataTransfer.setData('text/plain', text);
    
      target.dispatchEvent(
        new ClipboardEvent('paste', {
          clipboardData: dataTransfer,
    
          // need these for the event to reach Draft paste handler
          bubbles: true,
          cancelable: true
        })
      );
    
      // clear DataTransfer Data
      dataTransfer.clearData();
    }
    

    Check this link in case more info needed.

    0 讨论(0)
提交回复
热议问题