Paste content as plain text in summernote editor
Asked Answered
C

6

49

I need to copy paste some content in my summernote editor .But when I paste, it takes the style of the page from where I have copied it.I need to paste it as plain text. Is there any solution?

China answered 23/6, 2015 at 4:23 Comment(0)
S
117

Use the onPaste Callback

Use the onPaste option to define a callback that will strip the tags and manually insert the text.

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

Credit: https://github.com/summernote/summernote/issues/303

Solve Firefox Problems:

You may still have problems with Firefox. If so, wrap document.execCommand in a timer function to delay its execution a tiny bit:

setTimeout(function(){
    document.execCommand( 'insertText', false, bufferText );
}, 10);

Update for v0.7.0+

Position of callbacks in options is changed after v0.7.0
After v0.7.0, every callbacks should be wrapped by callbacks object. (source)

This means that the original code should be written as

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

Credit to Mathieu Castets for pointing this out (so if this bit helped, upvote his answer!)

TL;DR: Here's a functional demo

Superheat answered 24/6, 2015 at 6:50 Comment(11)
I tried the same.But onpaste event doesn't trigger.China
Any luck with the update? I've added a functional demo (though it's missing some 3rd party thing).Superheat
Yes, its working fine!!Problem was with the summernote.min.js file I guess.I was using the previous version of it.When I used the file given in the demo, the issue got fixed!!China
FOLLOWUP: ok almost... first paragraph (on every string of text i try) gets a <span> tag. After that it is all normal. @SuperheatNinefold
If you are on version 6.0 to 6.4 then you need onpaste instead of onPaste. version 6.5 fixes this.Fiance
I am currently using version 0.8.4 and I am noticing some formatting issues with additional spacing between lines? The solution above doesn't seem to work in IE. Is there another work around that may work?Konstanz
I can't figure out how to implement this solution in django and crispy forms, would really appreciate any kind of help. Link to questionDictation
As for the working demo (»TL;DR: Here's a functional demo«): Yes, indeed, it prevents text formats, like in-line styles. However – I can paste images from the clipboard, which will then be included as base64 encoded inline data. That's unfortunate. How can I prevent that?Shout
Love this solution! Simple and effective.Decline
Works like a charm! The best place to put this seemed to be where the editor is initialized and buttons, popovers - and callbacks - specifiedBagley
Does someone know if this solution falls under copyright? Once you understand it, it seems pretty simple. I don't know how to come up with a completely different solution other than maybe reading the clipboard in a slightly different way (if thats even possible).Sabadell
R
32

After v0.7.0, every callbacks should be wrapped by callbacks object. http://summernote.org/deep-dive/#callbacks

So if you are using summernote from v0.7.0 or above, jcuenod's answer could now be rewritten as:

$('.summernote').summernote({
    callbacks: {
        onPaste: function (e) {
            var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');

            e.preventDefault();

            // Firefox fix
            setTimeout(function () {
                document.execCommand('insertText', false, bufferText);
            }, 10);
        }
    }
});
Restrain answered 18/12, 2015 at 14:56 Comment(1)
as of tested today, works on firefox and safari. Works on Chrome too but chrome e.preventDefault() doesn't work, it still paste the content in if the content is a image even when bufferText.length == 0.Parabolic
S
10

The onPaste-callback works great but I was having problems with the different handling of linebreaks in different browsers. So I came up with the following solution, which uses html-linebreaks:



    $(".htmleditor").summernote({
      callbacks: {
        // callback for pasting text only (no formatting)
        onPaste: function (e) {
          var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
          e.preventDefault();
          bufferText = bufferText.replace(/\r?\n/g, '<br>');
          document.execCommand('insertHtml', false, bufferText);
        }
      }
    });

Sashasashay answered 3/4, 2018 at 13:59 Comment(0)
L
3

Managed to make a horrible hack work for IE11. This will sadly also ask for a paste permission from the user as well. If someone figures out a better suggestion I'm all ears.

var trap = false;
$(document).ready(function () {
    $('#summernote').summernote({
        callbacks: {
            onPaste: function (e) {
                if (document.queryCommandSupported("insertText")) {
                    var text = $(e.currentTarget).html();
                    var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');

                    setTimeout(function () {
                        document.execCommand('insertText', false, bufferText);
                    }, 10);
                    e.preventDefault();
                } else { //IE
                    var text = window.clipboardData.getData("text")
                    if (trap) {
                        trap = false;
                    } else {
                        trap = true;
                        setTimeout(function () {
                            document.execCommand('paste', false, text);
                        }, 10);
                        e.preventDefault();
                    }
                }

            }
        }
    })
})

JSFiddle

Lecturer answered 3/10, 2017 at 15:29 Comment(1)
This seems to do exactly what i needed, could u please give me a tip on how to use it or where to implement the above code in Django? Link to questionDictation
C
2

In my case, all of the above solutions did not work. By using those I found a solution, that works for me.

 $('#title').on('summernote.paste', function(e, ne) {
      var bufferText = ((ne.originalEvent || ne).clipboardData || window.clipboardData).getData('Text');
      ne.preventDefault();
      bufferText = bufferText.replace(/\r?\n/g, '<br>');
      document.execCommand('insertHtml', false, bufferText);
  })
Cartogram answered 23/6, 2022 at 11:7 Comment(0)
T
0

onPaste for Rich Text Editor not working perfectly, we will need to interfere both paste as plain and paste (pasteHTML), we need to remove html and body tag out of clipboardData html and wrap them with span tag

import {stateFromHTML} from 'draft-js-import-html';

onPaste = (e) => {
    const clipboardData = ((e.originalEvent || e).clipboardData || window.clipboardData);
    const isPlainTextPasting = !clipboardData.types.includes("text/html");

    if (isPlainTextPasting) {
        let bufferText = clipboardData.getData("Text").replace(/\r?\n/g, '<br>');
        const blocksFromHTML = stateFromHTML(bufferText);

        // ignore default paste, only apply for plain text paste
        e.preventDefault();

        setTimeout(() => {
            const html = stateToHTML(blocksFromHTML);
            this.editor.summernote('pasteHTML', html);
        }, 10);
    }
    else {
        let bufferText = clipboardData.getData("text/html")

        // ignore default paste, only apply for plain text paste
        e.preventDefault();

        setTimeout(() => {
            const html = bufferText.replace(/^<html>\r?\n<body>\r?\n/, "")
                .replace(/\r?\n<\/body>\r?\n<\/html>$/, "")
            this.editor.summernote('pasteHTML', `<span>${html}</span>`);
        }, 10);
    }
}
Tortilla answered 18/1, 2023 at 2:48 Comment(2)
what is stateFromHtml ?Underlinen
Hi @CePur, it's import {stateFromHTML} from 'draft-js-import-html'; thanks for pointing it outTortilla

© 2022 - 2024 — McMap. All rights reserved.