0

I am trying to figure out a way to remove style properties from pasted HTML content into a CKEditor instance. I used the following to remove style attributes completely, but I actually want to keep the margin-left property.

CKEDITOR.on('instanceReady', function(ev) {
    ev.editor.on('paste', function(evt) {
        if (evt.data.type == 'html') {
            evt.data.dataValue = evt.data.dataValue.replace(/ style=".*?"/g, '');
         }
     }, null, null, 9);
});

The issue is, sometimes margin-left is just switched to the margin shorthand and extra data that I do not want is added to that.

I am looking into jQuery and Javascript methods to try and accomplish this, but I haven't had any success yet.

Sean
  • 1,758
  • 3
  • 20
  • 34

1 Answers1

0

You can apply properly configured Allowed Content Filter to the pasted data. See this answer to learn how to apply it to a string: Apply CKEditor Advanced Content Filter to a string

The only problem which you may have is that you cannot tell ACF to allow all elements and their attributes, you have to specify the elements. So the filter may look like this:

var filter = new CKEDITOR.filter(
    'p h1 h2 h3 img strong em ul ol li[*](*){margin-left}'
);

It will allow all attributes and classes, but only margin-left on these elements.


EDIT

There's an easy way to list all elements:

var filter = new CKEDITOR.filter( {
    '$1': {
        // Use the hash containing all correct HTML elements
        // (plus some more things, but we can ignore them in this case).
        elements: CKEDITOR.dtd,
        attributes: true,
        classes: true,
        styles: 'margin-left'
    }
} );
Community
  • 1
  • 1
Reinmar
  • 21,729
  • 4
  • 67
  • 78
  • Will that only apply to content pasted in? Once it is in the editor, there may be additional styles applied to the content. I just want to filter it out before it is pasted in. – Sean Apr 11 '14 at 12:43
  • I just showed how to apply standalone filter to HTML string. If you'll do that in the paste event listener, that will only affect pasted content. – Reinmar Apr 11 '14 at 14:53
  • This works pretty well but I came up with a jQuery solution to use instead. When content gets pasted in, margin-left is never set. It uses the margin: x x x x short hand. I just need the left value from there but the CKEDITOR filter pulls out the margin all together. – Sean Apr 14 '14 at 12:46
  • Yes... this is a known limitation. And I'm about to hit it soon too, so hopefully I'll be able to solve it once and for all. – Reinmar Apr 14 '14 at 14:41