Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Filter JavaScript from properties and files

Shows how to sanitize potentially malicious JavaScript

A user can embed JavaScript in XhtmlString properties and in uploaded files (such as SVG images). Often this is intended, but sometimes it can be malicious.  Through configuration, you can specify the following options for MediaUploadMode, ScriptParserMode,  XhtmlString, LinkItem and Url when you upload a file with scripts or in other properties.

  • Keep = If the file contains JavaScript, then keep and execute it. If a property has JavaScript, allow it.
  • Remove = If the file contains JavaScript, remove the script before saving the file. If a property has JavaScript, remove it.
  • ThrowException = If the file contains JavaScript, do not upload the file and display an error in the upload dialog box. If a property has JavaScript, display an error.

The following example shows how to configure it programmatically.

[ModuleDependency(typeof (FrameworkInitialization))]
[InitializableModule]
public class ScriptParserInitialization: IConfigurableModule {
  public void ConfigureContainer(ServiceConfigurationContext context) {
    context.Services.Configure < ScriptParserOptions > (o => {
      // configure file upload
      o.MediaUploadMode = ScriptParserMode.ThrowException;
      o.MediaExtensionsToParse = new [] {
        ".svg"
      };

      // configure elements
      o.LoadingMode = ScriptParserMode.Keep;
      o.SavingMode = ScriptParserMode.ThrowException;
      o.Mode = ScriptParserOperationMode.Block;
      o.IllegalUriSchemes = new [] {
        "javascript"
      };
      // All events starting with "on" are considered illegal on div element.
      o.ElementAttributes.Add("div", "on*");
    });
  }
  public void Initialize(InitializationEngine context) {}
  public void Uninitialize(InitializationEngine context) {}
}