10

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?

jdehlin
  • 8,485
  • 3
  • 18
  • 33

2 Answers2

2

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.

Community
  • 1
  • 1
Rob Purcell
  • 1,285
  • 1
  • 9
  • 18
  • I'm doing something similar to this as a work around now. I've added a plain text box to the document type for "Page Scripts". This allows users to put page specific scripts in. – jdehlin Jan 21 '15 at 18:20
1

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

Grey Wolf
  • 5,801
  • 2
  • 25
  • 25