How to paste plain text in a Quill-based editor

ぐ巨炮叔叔 提交于 2020-02-21 12:00:48

问题


Quill (https://quilljs.com/) makes it simple to embed a quality text editor in a web page. When pasting html content in the editor, it filters the pasted html and then puts it into the text editor. My question is: How can I configure Quill so it pastes only plain text in the text editor? It would filter out all tags and leave the plain text only.

The documentation about the Clipboard module (http://quilljs.com/docs/modules/clipboard/) says that it is possible to add custom Matchers to the Clipboard, that will kind of filter the pasted text.

I don't know how to write a matcher that only allows plain text. Any help and any examples are much appreciated - thanks!


回答1:


After trial and error, I found the answer. The following matcher will cause the editor to paste plain text only:

quill.clipboard.addMatcher (Node.ELEMENT_NODE, function (node, delta) {
    var plaintext = $ (node).text ();
    return new Delta().insert (plaintext);
});

It uses jQuery. :)




回答2:


Couldn't get the answer to work. Here's another method that patches the clipboard module to accept plain text only.

GitHub Gist:

https://gist.github.com/ryanhaney/d4d205594b2993224b8ad111cebe1a13

Clipboard implementation:

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

class PlainClipboard extends Clipboard {
  onPaste (e) {
    e.preventDefault()
    const range = this.quill.getSelection()
    const text = 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()
  }
}

export default PlainClipboard

Example usage:

import Quill from 'quill'
import PlainClipboard from './PlainClipboard'

Quill.register('modules/clipboard', PlainClipboard, true)



回答3:


Updated solution of teusbenschop - works without jQuery and also fix problem with missing Delta object.

    quill.clipboard.addMatcher (Node.ELEMENT_NODE, function (node, delta) {
        var plaintext = node.innerText;
        var Delta = Quill.import('delta');
        return new Delta().insert(plaintext);
    });


来源:https://stackoverflow.com/questions/41237486/how-to-paste-plain-text-in-a-quill-based-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!