Laravel 5.7中Summernote编辑器粘贴纯文本功能实现求助
Hey there! Let's get that Summernote paste formatting issue sorted out for you. Your initial approach was on the right track, but there are a few tweaks we can make to ensure it works reliably with Summernote's internal mechanics.
The problem with your original code might be related to the deprecated document.execCommand method or how Summernote handles paste events under the hood. Let's try using Summernote's built-in methods instead, which are better optimized for the editor:
$(document).ready(function () { $('#input_description').summernote({ callbacks: { onPaste: function (e) { // Block the default paste behavior to stop formatted content from being inserted e.preventDefault(); // Grab plain text directly from the clipboard const clipboardData = (e.originalEvent || e).clipboardData || window.clipboardData; const plainText = clipboardData.getData('text/plain'); // Use Summernote's own pasteHTML method to insert the plain text, converting line breaks to <br> for proper display $(this).summernote('pasteHTML', plainText.replace(/\n/g, '<br>')); } } }); });
Here's why this works better:
- We use
text/plainexplicitly to fetch unformatted text, which has broader browser support than justText - Summernote's
pasteHTMLmethod integrates seamlessly with the editor, avoiding compatibility issues withdocument.execCommand(which is now deprecated in most browsers) - We convert line breaks from the plain text to
<br>tags so the content retains its basic line structure in the editor
If for some reason this still doesn't work (maybe due to a specific Summernote version quirk), you can try this fallback approach that cleans up the content right after paste:
$(document).ready(function () { $('#input_description').summernote({ callbacks: { onPaste: function (e) { const editor = this; // Add a tiny delay to let Summernote process the paste first, then overwrite with plain text setTimeout(function () { const currentContent = $(editor).summernote('code'); const plainText = $('<div>').html(currentContent).text(); $(editor).summernote('code', plainText.replace(/\n/g, '<br>')); }, 10); } } }); });
Just make sure your jQuery version is compatible with your Summernote setup—Laravel 5.7 typically uses jQuery 3.x, which works well with Summernote 0.8.x (the most common stable version around that Laravel release).
内容的提问来源于stack exchange,提问作者M.jottenheijm

