How to Remove Font Styles in TinyMCE

I use TinyMCE Editor on several of my projects, and I regularly have a problem with my users pasting content from Microsoft Word etc.

This means that I usually end up with multiple ugly font styles on the page that don’t match.

There is a relatively undocumented feature in TinyMCE called “valid_styles”.

This will prevent users from setting anything but the approved CSS attributes when entering or pasting content into the editor.

In my case I only wanted to allow font-weight, text-decoration, color, font-size and font-style.

Because the “valid_styles” option isn’t documented, most users were incorrectly trying to set it like so:

valid_styles : 'color,font-size,font-weight,font-style,text-decoration',

In fact it has to be set this way (as an array):

valid_styles : { '*' : 'color,font-size,font-weight,font-style,text-decoration' },

From what I can tell from examining the code, the first attribute defines what elements it applies to (in this case * means everything), and the second attribute is the list of allowed CSS styles.

So a complete example configuration could look something like this:

$('textarea').tinymce({
	// Location of TinyMCE script
	script_url : '../tinymce/jscripts/tiny_mce/tiny_mce.js',
	mode : "textareas",
	theme : "advanced",
	skin : 'o2k7',
	skin_variant : 'silver',
	plugins : "paste,table,contextmenu",
	theme_advanced_buttons1 : "fontsizeselect,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,code,|,help",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,removeformat,cleanup,|,undo,redo,|,outdent,indent,blockquote,|,bullist,numlist,|,link,unlink",
	theme_advanced_buttons3 : "tablecontrols",
	theme_advanced_toolbar_location : "top",
	theme_advanced_layout_manager : "SimpleLayout",
	theme_advanced_toolbar_align : "left",
	theme_advanced_path : "false",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : true,
	cleanup_on_startup : false,
	fix_list_elements : false,
	fix_nesting : false,
	fix_table_elements : false,
	valid_styles : {'*' : 'color,font-size,font-weight,font-style,text-decoration'},
	paste_use_dialog : true,
	paste_auto_cleanup_on_paste : true,
	extended_valid_elements : "a[name|href|target|title|onclick],img[src|border=0|alt|title|hspace|vspace|width|height|align],hr[width|size|noshade],font[size|color|style],span[align|style],h1,h2,h3,h4,h5,h6",
	content_css : "/wysiwyg_editor_rendering.css"
});

So now when a user pastes text in from Word, the font family is removed but everything else is left intact.

Original WYSIWYG Text

Cleaned WYSIWYG Text

Cleaned WYSIWYG Text

If you have any further information about this feature please feel free to post in the comments below.

You can leave a response, or trackback from your own site.

Leave a Reply

Powered by WordPress