Search code examples
tinymcetinymce-3

Force TinyMCE to strip out data- attributes


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


Solution

  • 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()
      )
    );