How to Add Valid Elements (like iframes) to TinyMCE version 2 in Episerver

March 2022 Update: This post was originally written for EPiServer version 11. In 2021, Episerver (now known as Optimizely) released version 12. While some parts of this post are outdated, other parts are still relevant and may be helpful. If you run into any issues when configuring TinyMCE, you should refer to Optimizely's official documentation. No content in this post has been changed for the current version.

With the breaking change release of Episerver CMS 11, the underlying functionality for TinyMCE has been moved into a separate NuGet package and updated to the next major version. One of the biggest changes with TinyMCE version 2 for Episerver, aside from the new editor based on TinyMCE v4, is that you can no longer customize the TinyMCE editor from the CMS Admin area. Now, all changes are done through code. and the way that you make these customizations have changed dramatically. So let's look at the new way to add valid elements into TinyMCE version 2 for Episerver.

A simple InitializationModule

A simple InitializationModule, specifically an IConfigurableModule, is all it takes to customize the TinyMCE editor to allow for additional valid elements.

[InitializableModule]
[ModuleDependency(typeof(TinyMceInitialization))]
public class CustomizedTinyMceInitialization : IConfigurableModule
{
  public void ConfigureContainer(ServiceConfigurationContext context)
  {
    context.Services.Configure<TinyMceConfiguration>(config =>
      config.Default()
        .AddSetting("extended_valid_elements", "iframe[*]")
    );
  }

  public void Initialize(InitializationEngine context) { }

  public void Uninitialize(InitializationEngine context) { }
}

This InitializationModule has a dependency on TinyMceInitialization, which provides the default configuration. We extend the default configuration with our "extended_valid_elements" setting, then provide the element configuration. You can learn more about the element configuration over at the TinyMCE documentation.

Some additional configuration

While we could stop after adding the setting, if you want to actually write and save the iframe tags in the text, we'll need access to the HTML view of the TinyMCE editor. Some additional configuration is needed.

There is minimal configuration needed to add the button that shows the underlying HTML of the TinyMCE editor. It can be added along with our settings in the InitializationModule.

context.Services.Configure<TinyMceConfiguration>(config =>
  config.Default()
    .AddSetting("extended_valid_elements", "iframe[*]")
    .AddPlugin("code")
    .AppendToolbar("code")
);

And that's it!

If you would like to learn more about the new way to customize the TinyMCE editor, check out the documentation on Episerver World.