Is there a way to stop TinyMCE from adding CDATA to <script> elements and from commenting out <style> elements?

Setting aside the concerns surrounding allowing <script> content within a Web editor, I am fully aware of them.

What I am interested in is permitting <style> and <script> elements within the text content. However, every time I attempt to do so in TinyMCE, it automatically changes them to:

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

and for script content, it alters it to:

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

In my TinyMCE initialization configuration, I have the following settings:

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

Despite these settings, I am struggling to find a solution that prevents TinyMCE from deactivating the <style> and <script> elements.

Answer №1

I highly recommend refraining from directly customizing third-party libraries whenever possible. Instead, I implemented a custom node filter on the editor's serializer during initialization by including the following in the configuration object passed to 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 solution will benefit others facing similar challenges.

Answer №2

To modify the tinymce.min.js, you can experiment with different lines of code.

,f.addNodeFilter("script,style",function(e,t){function n(e){return e.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,"")}for(var r=e.length,i,o,a;r--;)i=e[r],o=i.firstChild?i.firstChild.value:"","script"===t?(a=i.attr("type"),a&&i.attr("type","mce-no/type"==a?null:a.replace(/^mce\-/,"")),o.length>0&&(i.firstChild.value="// <![CDATA[\n"+n(o)+"\n// ]]>")):o.length>0&&(i.firstChild.value="<!--\n"+n(o)+"\n-->")}),f.addNodeFilter("#comment",function(e){for(var t=e.length,n;t--;)n=e[t],0===n.value.indexOf("[CDATA[")?(n.name="#cdata",n.type=4,n.value=n.value.replace(/^\[CDATA\[|\]\]$/g,"")):0===n.value.indexOf("mce:protected ")&&(n.name="#text",n.type=3,n.raw=!0,n.value=unescape(n.value).substr(14))})

If needed, feel free to delete or adjust any lines in the provided code snippet above.

Answer №3

After storing tinymce content, it is important to sanitize the output by removing certain tags. Here’s an example of how you can achieve this:

$sanitizedOutput = str_replace(array("// <![CDATA[", "// ]]>"), array("", ""), $_POST['tinymceContent']);

Once the output is sanitized, proceed to save it in the database.

Answer №4

In my experience, I found success by deleting the code that disables script tag formatting:

If (o.length > 0 && i.firstChild.value = "//<![CDATA[\n" + n(o) + "\n//]]>")

Additionally, to format the style tag, it's recommended to remove:

&&(i.firstChild.value = "<!--\n" + n(o) + "\n-->")

Answer №5

To prevent tinymce from recognizing style and script tags, consider using &lt; instead of <.

Here is an example:

For style:

&lt;style>th{width:80px}&lt;/style>

For script:

&lt;script>
$.address.unbind();
&lt;/script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

The reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-con ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Incorporate a Burger Icon into the Navigation Menu

insert image description here I am currently working on implementing a hamburger slide-out feature in my navigation bar. The desired behavior is for the sidebar to slide out to the right. We are using Elementor within WordPress for this project. Has anyone ...

Dealing with a jQuery/Javascript/AJAX response: sending a string instead of an integer as a parameter to a

Trying to figure out how to handle passing integers as strings in JavaScript within an AJAX response. Here is the code snippet: message+="<td class='yellow' onclick='open_flag("+i+j+")'>"; The message variable is eventually inse ...

Issue with Angular routing not functioning properly post form submission

Recently, I created a contact form using Angular for the frontend and NodeJs with Nodemailer for the backend. However, I encountered an issue where after submitting the form, instead of redirecting to the default page set in the app, the page remains on th ...

Create two grid components for Material-UI and use Flexbox to ensure that both items have equal height

I'm currently working on ensuring that two grid items have the same height using flex in Material UI, but I've hit a roadblock. It seems like my approach with the Grid element might be incorrect. I've experimented with adjusting the height a ...

"Exploring ways to create and save content in a different root folder within a nodejs project using my

In the process of developing my npm module, I am faced with the task of creating or writing a file in either the root directory or a specific folder within the nodejs project that will be utilizing my module. This includes users who will be implementing my ...

Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time. Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I ...

Having issues with jQuery not functioning on this specific web page across all browsers. The reason behind this puzzling dilemma remains elusive to me

I am experiencing issues with the functionality of my website. The buttons with + signs are meant to be drop-down toggles, and the mini-tabs below them should work as tabs. Additionally, the sample images at the bottom are not loading properly when clicked ...

Incorporating Imported Modules into the Final Build of a Typescript Project

In my Visual Studio Code Typescript project, I have set up some basic configurations and used npm to download libraries. One of the main files in my project is main.ts which includes the following code: import ApexCharts from 'apexcharts' var c ...

Incorporating a new text tag

Is there a way to add a text label for every circle that can be rotated and have its color changed? I'm looking for a solution that doesn't involve JSON data, but instead retrieves the necessary information from somewhere else. var w = 3 ...

The setTimeout function interrupts the event loop

Recently, I came across conflicting information regarding the usage of setTimeout to create nonblocking/asynchronous functions. One article suggested that using setTimeout is essential for this purpose, while another claimed that it actually blocks the eve ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

Find the total number of records in fnClick: (datatables.net)

I am struggling with some code where I need to retrieve the total number of records. I posted about it on the datatables.net forum but unfortunately, no one was able to help me... tableTools: { "sSwfPath": window.STATIC_BASE + "scripts/datatable/s ...

Display an aspx page within a div container

I am using the following code to load an aspx page in a div tag. Unfortunately, it's not working as expected. Can someone please assist me in resolving this issue? <script type="text/javascript"> $(document).ready(function () { $(&a ...

I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added ...

Aligning the .left position to make the border of a <div> synchronized

When working on my Jquery program, I encountered an issue with borders not aligning properly within the container. Specifically, in the execution (where the container is represented by a white box), the left border extends beyond the position().left proper ...

What is the best way to make a flexbox stretch to fill the entire screen

Can someone guide me on how to ensure my flexbox expands to fill the entire screen? I am working on a website and I want to eliminate any empty spaces from it. >> I have attempted setting margin and padding to zero but it doesn't seem to work :/ Th ...