Stop HTML Editor in Nop Commers Stripping out Javascript and HTML (TinyMCE)

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
9 years ago
Hi,

How can I stop the page editor in NOP from Stripping out HTML, I have the following line in one of my pages carried over from NOp 2.50 to Nop 3.30 and the line in nop 2.5 shows this

<div class="genericpadder"><a onclick="showprices();" href="#"><img src="../../../images/Buy-now1.jpg" alt="" width="100" height="31" /></a></div>

But in 3.30 it end up looking like this after I hit the save button

<div class="genericpadder"><a  href="#"><img src="../../../images/Buy-now1.jpg" alt="" width="100" height="31" /></a></div>

It takeing the following out onclick="showprices();"

I need the onclick to be there, so is there a way to stop it stripping the onlcick even, as we have put all our prices in to a div this displayed when the customer presses on the Buy button, this works fine in NOP 2.50 but on 3.30 it seems as I said to stip out the onclick="showprices();" event.

Can any one tell me how to stop this from happending.
9 years ago
Hi,

NopCommerce uses TinyMCE editor for filling out product, category or some other description in the administration. Since version 4 of this editor all inline JS attributes are stipped by default.

You are not the first who had this issue. You could read more about it in TinyMCE forum - http://www.tinymce.com/forum/viewtopic.php?id=31574.
You will have to edit the editor initialization that could be found in Presentation\Nop.Web\Administration\Views\Shared\EditorTemplates\RichEditor.cshtml view (This path applies to source code version).

Hope this helps!
9 years ago
Hi,

Thanks for that I edited C:\demowebsites\nopCommerce_3.30_NoSource(1)\Administration\Views\Shared\EditorTemplates\RichEditor.cshtml, and changed the following:

@model String
@using Nop.Services.Security
@using Nop.Web.Framework.UI;
@{
    //we do not bundle this script file (does not work for some reasons in bundle)
    Html.AddScriptParts("~/Content/tinymce/tinymce.min.js", true);
    
    var permissionService = EngineContext.Current.Resolve<IPermissionService>();
    var canUploadPictures = permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures);

    //we have to temporary disable picture uploading
    //because "jbimages" plugin require "relative_urls" settings set to "false".
    canUploadPictures = false;
}
<script>
    $(document).ready(function() {
        tinymce.init({
            selector: "#@ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty)",
            height: 350,
            width: 790,
            cleanup_on_startup: false,
            trim_span_elements: false,
            verify_html:false,
            cleanup: false,
            convert_urls: false,
            valid_elements : "a[href|target=_blank|onclick]",
            extended_valid_elements : "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]",
            plugins: [
                "advlist autolink lists link image charmap print preview anchor",
                "searchreplace visualblocks code fullscreen",
                "insertdatetime media table contextmenu paste@(canUploadPictures ? " jbimages" : null)"
            ],
            toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image@(canUploadPictures ? " jbimages" : null)",
            //"relative_urls" required by jbimages plugin to be set to "false"
            //but in this case it'll break existing links (e.g. message template tokens)
            relative_urls: true
        });
    });
</script>
@Html.TextArea(string.Empty, /* Name suffix */
    ViewData.TemplateInfo.FormattedModelValue /* Initial value */
)

ALso updated tiny mce to the latest version off there web site and that seems to have fixed the problems.

Thanks again.
4 years ago
Hi,

I'm trying to make a new topic, but as we know, CSS or JS input is removed on saving.  I've tried following the various links above, but these no longer seem to match up with version 4.2 that we're now on.

Which bit of this needs to be changed for it to allow basic CSS?

Thanks

@model string
@inject IPermissionService permissionService
@inject AdminAreaSettings adminAreaSettings
@using Nop.Web.Areas.Admin.Helpers
@using Nop.Core
@using Nop.Services.Security
@using Nop.Web.Framework.UI
@{
    //we do not bundle this script file (does not work for some reasons in bundle)
    Html.AddScriptParts("~/lib/tinymce/tinymce.min.js", excludeFromBundle: true);

    // tinyMCE language
    var language = TinyMceHelper.GetTinyMceLanguage();

    var allowJbimages = false;
    var allowRoxyFileman = permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures);

    var random = CommonHelper.GenerateRandomInteger();

    //extend editor with additional settings
    //Sample setting value (below):
    //settings.plugins.push('print'); settings.toolbar += ' | print';
    var additionalEditorSettings = adminAreaSettings.RichEditorAdditionalSettings;
    //is java-script supported?
    var allowJavaScript = adminAreaSettings.RichEditorAllowJavaScript;

    //allow HTML body? Full page? - http://www.tinymce.com/wiki.php/Plugin:fullpage
    //false by default
    var enableFullPage = Convert.ToBoolean(ViewData["nop.RichEditor.EnableFullPage"] ?? false);

    var extended_valid_elements = new List<string>();
    var valid_children = new List<string>();
    
    if(allowJavaScript)
    {
        extended_valid_elements.Add("script[charset|defer|language|src|type]");
        valid_children.Add("+body[script]");
    }

    if (adminAreaSettings.RichEditorAllowStyleTag)
    {
        extended_valid_elements.Add("style[dir<ltr?rtl|lang|media|title|type]");
        extended_valid_elements.Add("link[dir<ltr?rtl|href|hreflang|lang|media|rel|rev|title|target|type]");

        valid_children.Add("+body[style]");
        valid_children.Add("+body[link]");
    }
}

<script>
    $(document).ready(function() {
        @* wooncherk contribution *@
        function RoxyFileBrowser@(random)(field_name, url, type, win) {
            //we manually generate the configuration file to ensure that it works fine in virtual directory
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.Action("CreateConfiguration", "RoxyFileman"))",
                success: function (data, textStatus, jqXHR) {
                    var roxyFileman = '@Url.Content("~/lib/Roxy_Fileman/index.html")';
                    if (roxyFileman.indexOf("?") < 0) {
                        roxyFileman += "?type=" + type;
                    } else {
                        roxyFileman += "&type=" + type;
                    }
                    roxyFileman += '&input=' + field_name + '&value=' + document.getElementById(field_name).value;
                    tinyMCE.activeEditor.windowManager.open({
                        file: roxyFileman,
                        title: 'Roxy Fileman',
                        width: 850,
                        height: 650,
                        resizable: "yes",
                        plugins: "media",
                        inline: "yes",
                        close_previous: "no"
                    }, { window: win, input: field_name });
                    return false;
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('#createConfigurationFailed-info').text(errorThrown);
                    $("#createConfigurationFailed").click();
                }
            });
        }

        var defaultEditorSettings@(random) = {
            selector: "#@Html.IdForModel()",
            fontsize_formats: "8pt 9pt 10pt 11pt 12pt 26pt 36pt",
            height: 200,
            width: '100%',
            autoresize_min_height: 200,
            autoresize_max_height: 200,
            plugins: [
                "advlist autolink autoresize directionality lists link image charmap preview anchor",
                "searchreplace visualblocks code fullscreen textcolor",
                "insertdatetime media table contextmenu paste@(allowJbimages ? " jbimages" : null)@(enableFullPage ? " fullpage" : null)"
            ],
            toolbar: "ltr rtl | insertfile undo redo | styleselect | fontselect | fontsizeselect | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image@(allowJbimages ? " jbimages" : null)",
            //"relative_urls" required by jbimages plugin to be set to "false"
            relative_urls: false,
            @if (allowRoxyFileman)
            {
                <text>
                    //picture manager
                    file_browser_callback: RoxyFileBrowser@(random),
                </text>
            }
            @if (!string.IsNullOrEmpty(language))
            {
                <text>
                    //language
                    language: "@language",
                </text>
            }
            //we should set "convert_urls" set to "false" (because of "relative_urls" requirement)
            //otherwise, it'll break existing links when editing message template
            convert_urls: false,
            //ensure that special chars are not encoded. For example, ä, ö and ü should NOT become "&auml;", "&ouml;" and "&uuml;"
            //Otherwise, database searches become impossible when words contain a character of this kind
            entity_encoding: "raw",
            @if (allowJavaScript)
            {
                <text>
                    allow_script_urls: true,
                </text>
            }
            else
            {
                <text>
                    invalid_elements: "script",
                </text>
            }
            @if (extended_valid_elements.Any())
            {
                <text>
                    extended_valid_elements: "@Html.Raw(string.Join(',', extended_valid_elements))",
                </text>
            }
            @if (valid_children.Any())
            {
                <text>
                    valid_children: "@Html.Raw(string.Join(',', valid_children))"
                </text>
            }
        };

        function getAdditionalEditorSettings@(random)(settings) {
            @Html.Raw(additionalEditorSettings)
            return settings;
        }

        tinyMCE.init(getAdditionalEditorSettings@(random)(defaultEditorSettings@(random)));
    });
</script>

<textarea asp-for="@Model">@ViewData.TemplateInfo.FormattedModelValue</textarea>
<nop-alert asp-alert-id="createConfigurationFailed" />
3 years ago
Hey cookbot did you ever figure out this issue? I'm facing the same thing and the previous answer is very outdated.
3 years ago
Im having saving challenge, nop 4.2.. any help will be appreciated
3 years ago
YourSite.com/Admin/Setting/AllSettings

Set: RichEditorAllowJavaScript=True
3 years ago
Enabling Javascript isn't enough....
I tried just putting the valid_elements into it like this:
convert_urls: false,
valid_elements: "a[href|target=_blank|onclick]",
entity_encoding: "raw",
            @if (allowJavaScript)
            {
                <text>
                    allow_script_urls: true,
                </text>
            }
            else
            {
                <text>
                    invalid_elements: "script",
                </text>
            }

...and it no longer strips the onclick from my content!!

BUT...by doing so, it is as if I have made all other elements invalid and they are now being stripped...(divs, spans,classes, iframe, etc....)

Is it the case that if you add ANY valid elements, you must define EVERY valid element? Any clues for me??
3 years ago
Ok, I found the TinyMCE documentation...that's how it works....if you define any valid elements, you must define them all....
OR..if the editors are all in your admin area, and none available for the public to use, you can just use this and it will allow all possible HTML elements:
      valid_elements : '*[*]',


Be aware, though, that if you allow the public to use your rich text editors, they could inject malicious code.
2 years ago
We ran into this issue as well, all of our onclick attributes were being stripped off in the editor.

Our initial fix , thanks to this thread was to add
 extended_valid_elements.Add("input[onclick]"); 
to the RichEditor.cshtml file under “\Areas\Admin\Views\Shared\EditorTemplates\”.

This worked, but just as embryo pointed out it stripped out all the other attributes and our input buttons became text inputs.

We found a post at stack overflow that helped us figure out which attributes should (maybe) be allowed for input elements:
https://stackoverflow.com/questions/21281161/tinymce-4-valid-elements-default-rule-set

We extended the valid elements to include input with a whole slew of attributes that were listed in the stack overflow post, right after the add ->script:

    if(allowJavaScript)
    {
        extended_valid_elements.Add("script[charset|defer|language|src|type]");

        extended_valid_elements.Add("input[alt|autocomplete|checked|dirname|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|list|max|maxlength|min|multiple|name|pattern|readonly|required|size|src|step|type|value|width|usemap|align|onclick]");

        valid_children.Add("+body[script]");
    }


Not sure if this was exactly how to do this as the element obviously existed before, but it works on our development site.

Anyway, is this something we even want to do?
(There must be some reason the onclick event is no longer allowed.)

Is there a way to just add the onclick attribute to input elements without restating the full list of attributes allowed?

Is there a better way to do this?
(We are just trying to enable existing code, but we could replace it with something more appropriate.)

Thanks,

-Dale
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.