Can't add javascript to rich text editor
Asked Answered
P

2

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?

Pledget answered 14/1, 2015 at 22:10 Comment(0)
B
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.

Bisulcate answered 21/1, 2015 at 1:19 Comment(1)
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.Pledget
T
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

Trophoblast answered 23/7, 2015 at 3:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.