Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ckeditor 4 - removing nbsp; and <p></p> after paste from Word

When pasting from Word, the clean-up in Ckeditor 4 is generally excellent. However I have noticed two things, when the Word doc is not ideally formatted:

  1. If a Word doc contains "&nbsp;&nbsp;" this is replicated as is in Ckeditor. I want to simple insert "" on paste.

  2. Pasting from Word often creates "<p>&nbsp;</p>". I have partly fixed this by using fillEmptyBlocks = false, which means I am left with "<p></p>".

I'm not sure how I can add an additional javascript function to extend Ckeditor's functionality to tackle these. Ckeditor 4 offers an Advanced Content Filter, but the documentation is frankly baffling to me and it's not clear if it can do the above.

This is my current CKeditor config.js:

CKEDITOR.editorConfig = function( config ) {
    config.toolbar = <removed>;
    config.format_tags = 'p;h2;h3;div';
    config.contentsCss = '/css/site.min.css';
    config.height = 500;
    config.removePlugins = 'elementspath';
    config.resize_enabled = false;
    config.allowedContent = true;
    config.fillEmptyBlocks = false;
};

I have attempted this Ckeditor 3 style approach, which doesn't appear to work. evt.data.dataValue does contain the HTML from the editor though.

CKEDITOR.on('instanceReady', function(ev) {
  ev.editor.on('paste', function(evt) { 
    evt.data.dataValue = evt.data.dataValue.replace('&nbsp;','');
    evt.data.dataValue = evt.data.dataValue.replace('<p></p>;','');
    console.log(evt.data.dataValue);
  }, null, null, 9);
});

Answer must include making this work via some form of Ckeditor on paste event, function that interacts with Ckeditor or via ACF. Please don't suggest doing this in PHP on-save, I regard that as a last resort and would be able to do that myself.

Thanks!

like image 469
Ben Avatar asked Dec 20 '22 03:12

Ben


1 Answers

Figured it out after a lot of debugging. The approach in the question was actually spot on, but I mistakenly assumed the JS replace function did a global replace. So what was happening was only the first instances were being removed. Here is the amended version that uses regex style syntax, replacing globally:

CKEDITOR.on('instanceReady', function(ev) {
  ev.editor.on('paste', function(evt) { 
    evt.data.dataValue = evt.data.dataValue.replace(/&nbsp;/g,'');
    evt.data.dataValue = evt.data.dataValue.replace(/<p><\/p>/g,'');
    console.log(evt.data.dataValue);
  }, null, null, 9);
});
like image 56
Ben Avatar answered Dec 30 '22 10:12

Ben