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

React-dnd enhances the functionality of the MUI tree view

I've been using a Material UI v4 Treeview with react-dnd and everything works smoothly. However, when I recently upgraded to MUI v5 Treeview, the drag functionality stopped working - the item is no longer draggable. After comparing the two TreeItem im ...

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...

The styles for the React calendar are not being properly applied to the calendar component due to CSS overriding

Having trouble overriding the default Calendar.css file in NextJS while creating a calendar component. Even after adding my own custom styles, they aren't being applied. Deleting the css file contents doesn't change the format either. Only when c ...

No specified margin at the top of the website's header section

My task was to design the header section of a webpage to resemble this desired webpage look. I started by creating a "header" tag as a container and added a navbar within it. To display the items, I used an unordered list with CSS adjustments for a horizon ...

Turn off and then turn on user input without exiting the textarea

I've been working on a small project that requires me to enable and disable text input in a textarea using key commands, similar to Vi/Vim's insertion and command modes. However, I'm struggling to find an elegant solution. Disabling the tex ...

Unable to send a namespaced action from a different module: [vuex] action type is not recognized

In my coding project, I am working with two different modules called activities and alerts. One of the requirements is that whenever an activity is added, I need to trigger an alert action with the namespaced identifier alerts/SHOW. This functionality was ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

jQuery - Wait for the completion of one UI change before initiating another UI change

Is there a way to implement the functionality where $("#login").toggle("drop", {direction: "left"}); is executed first and upon completion, $("#register").toggle("drop", {direction: "right"}); is then carried out? The issue arises from the fact that the ...

Fill every empty element with elements from another array

I'm struggling to grasp the concept of arrays. I have two arrays and I want to replace the null elements in one with the elements from the other. Here is what I have currently: var arr1 = [1,2,3,4] var arr2 = [null, 99, null, null] arr2.map((item) = ...

Having trouble implementing a CSS style for a Kendo-checkbox within a Kendo-treeview component

I am facing a The issue I am encountering is that while the CSS for k-treeview is being applied from the scss file, it is not being applied for the kendo-checkbox I attempted to resolve the problem by using the following code: <kendo-treeview ...

Timeout error occurred in Async.js because the callback was already triggered

Whenever I execute index.js, I encounter an ETIMEDOUT or ECONNRESET error followed by a Callback was already called error. Initially, my assumption was that the issue stemmed from not including a return before calling the onEachLimitItem callback. Consequ ...

The Art of CSS Arrangement

I'm experiencing an issue on my website PSR Is there a way to ensure that the Footer always appears below the content div automatically? Both the Content and the Footer have relative positioning. Additionally, how can I make the Footer the same siz ...

What is the method for obtaining the WordPress user ID?

I am looking to incorporate a Twitter follow button for all site authors on every post. Below is the structure of the Twitter button: <a href="https://twitter.com/twitterapi" class="twitter-follow-button" data-show-count="false" data-lang="en">Foll ...

Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result. Here is my current code: axios .post("/post ...

Tips for displaying HTML content in an AJAX success alert message with ASP.NET MVC and jQuery

I have an action result that sends content in the following format: public ActionResult MyAction() { string mystring = //doing something return Content(mystring , "html"); } Client Side: $.ajax({ url: "/MyController ...

Node.js Promise Rejection: TypeError - Unable to access property 'sign' because it is undefined

tran_script.js const CoinStack = require('coinstack-sdk-js'); const coinstackClient = new CoinStack('YOUR_COINSTACK_ACCESS_KEY', 'YOUR_COINSTACK_SECRET_KEY'); // Actual keys not displayed const privateKeyWIF = CoinStack.ECK ...

Using Javascript to make a call to load or post with jQuery

I'm not dealing with Ajax this time, but rather with JavaScript initializations. Is there a way to automatically update all the loaded elements when using $(element).load(...), in order to, for example, create a rangeInput element from an input type ...

Facing issues with Heroku and Express/Nodejs crashing?

I have been working on a React/Express application that I am attempting to deploy on Heroku. While trying to do so, I encountered the following errors in my logs: 2020-01-13T03:39:48.733455+00:00 heroku[router]: at=error code=H10 desc="App crashed" method ...

Transferring an object from one inventory to another

I'm in the process of developing a task manager that enables users to add and remove tasks. I am also working on enabling the ability for users to transfer tasks from one list to another. The current code I have written doesn't seem to be functio ...