Categories
JavaScript Answers

How to Paste Content as Plain Text Into the Summernote Editor?

Spread the love

To paste content as plain text into the Summernote editor, we add our own onPaste callback that calls the document.execCommand method.

For instance, we can write:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote.min.js" integrity="sha512-kZv5Zq4Cj/9aTpjyYFrt7CmyTUlvBday8NGjD9MxJyOY/f2UfRYluKsFzek26XWQaiAp7SZ0ekE7ooL9IYMM2A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.css" integrity="sha512-pDpLmYKym2pnF0DNYDKxRnOk1wkM9fISpSOjt8kWFKQeDmBTjSnBZhTd41tXwh8+bRMoSaFsRnznZUiH9i3pxA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div id="summernote">Hello Summernote</div>

to add the jQuery and Summernote libraries and the Bootstrap and Summernote CSS.

We also add the div that we will use for the Summernote editor.

Then we write:

$('#summernote').summernote({
  callbacks: {
    onPaste(e) {
      const bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
      e.preventDefault();
      document.execCommand('insertText', false, bufferText);
    }
  }
});

We call summernote with an object that has the callbacks.onPaste method.

In the method, we get the pasted text with:

const bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');

Then we call e.preventDefault to stop the default behavior.

Finally, we write:

document.execCommand('insertText', false, bufferText);

to paste plain text.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *