Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent TinyMCE from adding CDATA to <script> tags and from commenting out <style> tags?

Let's put aside the issues of allowing <script> content inside a Web editor; I'm perfectly aware of them.

What I want is to allow <style> and <script> elements inside the text content, the issue is that, whenever I do this, TinyMCE changes them to:

<style><!-- th{width:80px} --></style> 

and the script content is changed to:

<script>// <![CDATA[ $.address.unbind(); // ]]></script> 

On my TinyMCE init configuration, I have:

valid_elements : "*[*]", extended_valid_elements : "*[*],script[charset|defer|language|src|type],style", custom_elements: "*[*],script[charset|defer|language|src|type],style", valid_children : "+body[style],+body[script]", verify_html : false, media_strict: false 

But I can't seem to find a way to prevent TinyMCE from disabling the <style> and <script> elements.

like image 399
out_sid3r Avatar asked Mar 11 '15 10:03

out_sid3r


1 Answers

I would recommend avoiding any direct customization to third party libraries if it can be avoided. Instead I added a custom node filter to the editors serializer during initialization by adding the following to the config object passed into the tinymce construction call:

init_instance_callback : function(editor) {     // jw: this code is heavily borrowed from tinymce.jquery.js:12231 but modified so that it will     //     just remove the escaping and not add it back.     editor.serializer.addNodeFilter('script,style', function(nodes, name) {         var i = nodes.length, node, value, type;          function trim(value) {             /*jshint maxlen:255 */             /*eslint max-len:0 */             return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')                     .replace(/^[\r\n]*|[\r\n]*$/g, '')                     .replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '')                     .replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');         }         while (i--) {             node = nodes[i];             value = node.firstChild ? node.firstChild.value : '';              if (value.length > 0) {                 node.firstChild.value = trim(value);             }         }     }); } 

Hopefully this will help others stuck in the same boat.

like image 170
Jonmark Weber Avatar answered Oct 10 '22 01:10

Jonmark Weber