Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add javascript to rich text editor

I'm trying to allow javascript in rich text editor inputs in my Umbraco setup. I'm using Umbraco 7.2. I've enabled the script tag in tinyMceConfig.config so the editor no longer eats my script tags. The problem now is that my content is cut off.

For example, in my RTE I put:

<p>before</p>
<script>
alert('blam');
</script>
<p>after</p>

This get's transformed by TinyMCE to:

<p>before</p>
<script>// <![CDATA[
alert('blam');
// ]]></script>
<p>after</p>

The problem is the value of Umbraco.Field("myRte") ends up being:

<p>before</p>
<script>// <![CDATA[
alert('blam');
// ]]

It seems related to CDATA. Does anyone else have javascript in RTE working in Umbraco 7?

like image 440
jdehlin Avatar asked Jan 14 '15 22:01

jdehlin


2 Answers

A possible workaround would be to create a macro that would allow you to insert a script into the RTE. The macro would have a single Textarea parameter where you would paste in your script tag, and you would simply render the parameter value as raw Html. However, it might be a good idea to check that the input is valid html before you attempt to render it on the page.

If you use a razor macro the partial view could look like this:

@inherits Umbraco.Web.Macros.PartialViewMacroPage
@{
    var script = Model.MacroParameters["script"].ToString();
}

@if (!script.IsNullOrWhiteSpace())
{
    @Html.ValidateHtml(script)
}

Where ValidateHtml is an extension method to the Mvc HtmlHelper:

    public static IHtmlString ValidateHtml(this HtmlHelper helper, string input)
    {
        if (!string.IsNullOrEmpty(input))
        {
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(input);
            if (htmlDoc.ParseErrors.Count() == 0)
            {
                return new MvcHtmlString(input);
            }
        }

        return null;
    }

The helper method uses the Html Agility Pack and I got the code from an answer posted to another SO question.

I've tested this on an Umbraco 7.2.1 install and it works fine even if you select the "Render in rich text editor and the grid" option.

like image 128
Rob Purcell Avatar answered Oct 26 '22 07:10

Rob Purcell


My solution is not write direct script in editor, write it in a test.js file after that include

<script src="https:/....test.js></script>

In tiniMceConfig.config file (config folder) validElements tag, add this

,script[type|src|language]

so it will look like this

    <![CDATA[+a[id|style|rel
.....
,bdo,button,script[type|src|language]]]>

Test and work on Umbraco 4.7.x. I'm not test on umbraco 7

like image 42
Grey Wolf Avatar answered Oct 26 '22 05:10

Grey Wolf