1

I am using onPaste function in quill editor. But whenever I tried to paste some text, the text get started as below format. How can I display them as the same content copied from?

Below is the code that I had used in order to get either html/text or plain/text

import Quill from 'quill'
const Clipboard = Quill.import('modules/clipboard')
const Delta = Quill.import('delta')

class PlainClipboard extends Clipboard {
   onPaste(e) {
    e.preventDefault()
    this.quill.focus();
    const range = this.quill.getSelection()
    const text = e.clipboardData.types.find(type => type == "text/html") == "text/html" ? e.clipboardData.getData('text/html') 
                : e.clipboardData.types.find(type=>type == "text/rtf") == "text/rtf" ? e.clipboardData.getData('text/html') 
                : e.clipboardData.getData('text/plain');
    const delta = new Delta()
      .retain(range.index)
      .delete(range.length)
      .insert(text)
    const index = text.length + range.index
    const length = 0
    this.quill.updateContents(delta, 'silent')
    this.quill.setSelection(index, length, 'silent')
    this.quill.scrollIntoView()
}

Read highlighted "Test" content is copied and pasted but instead of displaying as it was before, the chuck of html code is displayed.

enter image description here

susmita rai
  • 39
  • 2
  • 20

1 Answers1

0

If I understand correctly, the whole point of this clipboard is to paste the contents as plaintext?

Your issue is that you're directly retrieving the text/html clipboard entry and just inserting it, which is always going to be raw HTML (that's the whole point of it).

The way to fix your current solution is to just ask for text/plain, which will give you the plain text you're after:

const text = e.clipboardData.getData('text/plain');

That being said, I'd actually go with a different approach altogether. I wouldn't recommend rewriting the Clipboard module if you can avoid it. Instead, you should use the APIs Quill exposes, and use clipboard matchers, which let you respond to the clipboard and modify the Delta that way.

For example, this matcher will strip all formatting on anything being pasted in by simply stripping the attributes property from the ops:

quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
  const ops = delta.ops.map((op) => ({insert: op.insert}));
  return new Delta(ops)
})

Working example here.

Alec
  • 2,432
  • 2
  • 18
  • 28