3

I'm using the TinyMCE plugin and have the valid_elements option is set to:

"a[href|target:_blank],strong/b,em/i,br,p,ul,ol,li"

Even though data- attributes aren't listed, TinyMCE doesn't strip them out. It seems to strip out all other non-listed attributes, but for some reason, data- attributes (e.g. data-foo="bar") are an exception. How can I get TinyMCE to strip out data- attributes?

I'm using TinyMCE version 3.4.7

Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275

2 Answers2

4

This is how I solved this problem. I manually changed the HTML that TinyMCE produces by running it through this function:

var stripDataAttributes = function(html) {

  var tags = html.match(/(<\/?[\S][^>]*>)/gi);
  tags.forEach(function(tag){
    html = html.replace(tag, tag.replace(/(data-.+?=".*?")|(data-.+?='.*?')|(data-[a-zA-Z0-9-]+)/g, ''));
  });

  return html;
};

Here's a jsbin for it: https://jsbin.com/lavemi/3/edit?js,console

Here's how you can use it:

tinyMCE.activeEditor.setContent(
  stripDataAttributes(
    tinyMCE.activeEditor.getContent()
  )
);
Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275
  • 3
    I have to ask, if 5 years later this is the best way, because I'm having the exact same issue with TinyMCE 5, specifically inside List Items when copied from Word – Meeker Feb 22 '21 at 20:59
0

Tinymce version 5 vs 6, I use this:

var stripAttributes = function(html) {
  var tags = html.match(/(<\/?[\S][^>]*>)/gi);
  tags.forEach(function(tag){
    // Remove "class" attributes
    var noClass = tag.replace(/(class=".*?")|(class='.*?')|(class=[^\s>]*)/gi, '');

    // Remove "id" attributes
    var noID = noClass.replace(/(id=".*?")|(id='.*?')|(id=[^\s>]*)/gi, '');

    // Remove "data-" attributes
    var noData = noID.replace(/(data-.+?=".*?")|(data-.+?='.*?')|(data-[a-zA-Z0-9-]+)/gi, '');
    // Update html string
    html = html.replace(tag, noData);
  });
  return html;
};

And:

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  toolbar: 'paste',
  paste_preprocess : (editor, args) => {
            console.log("before" , args.content);
            args.content  = stripAttributes(args.content);
            console.log("after" , args.content);
        },
});
Hoàng Vũ Tgtt
  • 1,863
  • 24
  • 8