Search code examples
tinymcetinymce-4tinymce-5

TinyMCE 5 not cleaning attributes from tags


TinyMCE 5 just won't clean all the attributes from tags. It leaves stuff like "data-gps-track, data-controller, aria-label:"" ". It cleans stuff like "href, style, class". Any idea what's the problem here?

tinymce.init({
        selector: "#mytextarea",
        plugins: "paste, code",
        toolbar: "edit, code",
        paste_block_drop: false,
        paste_tab_spaces: 2,
        paste_as_text: cleantext,
        valid_elements: "a,code,p",
      });

You can try pasting stuff off StackOverflow, where these attributes are present.


Solution

  • I have ended up using an answer from this StackOverflow answer. I have also added a filter for clearing aria attributes to the regex.

    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-]+)|(aria-.+?=".*?")|(aria-.+?='.*?')|(aria-[a-zA-Z0-9-]+)/g,
              ""
            )
          );
        });
    
        return html;
      };
    
    tinymce.init({
        selector: "#mytextarea",
        plugins: "paste, code",
        toolbar: "edit, code",
        paste_block_drop: false,
        paste_tab_spaces: 2,
        paste_as_text: cleantext,
    
        valid_styles: {
          "*": "",
          p: "color",
        },
        // https://www.tiny.cloud/docs-4x/configure/content-filtering/
    
        // valid_elements: "*[*|-href]",
        // https://www.tiny.cloud/docs-3x/reference/Configuration3x/Configuration3x@valid_elements/
        // jen pozor na mezery (když jsem měl  valid_elements: "a, code, p" , tak mi to nešlo!)
        paste_preprocess: function (plugin, args) {
          args.content = stripDataAttributes(args.content);
          //   args.content = args.content.replace(cleanElements, "$1>");
        },
      });