Sitecore RTE Button Postprocessing

There may be times that you want to modify the way stock Sitecore RTE buttons work without actually modifying stock Sitecore files.  An easy way to accomplish this is to override the Telerik editor commands manually using a custom js file.

Some common uses of this technique could include

  1. Adding classing to injected elements.
  2. Wrapping injected elements in a wrapping element.
  3. Adding a sibling html element for an icon perhaps.
  4. Modifying the markup for SEO needs.
  5. Modifying the markup to build a responsive website.

Find the operation to patch

The first thing you need to do is find the RTE command for the button you’d like to add post processing to.  Easiest way to do this is by using your browsers inspect feature on the button you’d like to enhance.

finding-command

The class of the span element that makes up the button is the name of the command you’re interested in.  At this point you can start writing your javascript.

The Javascript

var	RadEditorCommandList = Telerik.Web.UI.Editor.CommandList;

var table = RadEditorCommandList["InsertTable"];
RadEditorCommandList["InsertTable"] = function (commandName, editor, args) {
	table(commandName, editor, args);
	var p = editor.getSelectedElement().parentNode.parentNode.parentNode;
	p.classList.add("editor-table")
};

This code will modify the insert table button to add a class of editor-table to the table after it’s injected.

So what are we doing here, let’s analyze it.

  1. Get the telerik editor command list object.  This object stores the javascript that drives each of the buttons in the editor.
  2. Save the original command into a custom variable called table
  3. Replace the method attacked to the telerik editor command list with our own function
  4. Using the telerik editor object to get the selected element after the table is inserted and traverse up to the
    node
  5. Add a class of editor-table to the table root

 
You’ll likely need to utilize the debugger to drop breakpoints down in your code and use the console to identify the correct element you’ll need to manipulate.

Having Sitecore add your javascript to the editor

There’s a simple config patch to add your javascript to the RTE editor.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
	<sitecore>
		<clientscripts>
			<htmleditor>
				<script key="customsrc" src="/relative/path/to/customSitecore.js" language="JavaScript"/>
			</htmleditor>
		</clientscripts>
	</sitecore>
</configuration>

Using this method is not limited to ONLY postprocessing, but you could essentially take stock methods and do whatever you please with them. Sky’s the limit, so go have fun with it.