FCKeditor HTML Injection

by Matt 28. June 2009 23:42

 

Update 2010-02-10 - I have resolved the issue with Firefox.  See this post for information.

I spent a bit of time today trying to inject HTML into an fckeditor instance.  Whenever I would give the fckeditor the value to display, it would display all the html, rather than rendering it.  I found a neat little project that helped me to overcome where I was going wrong here.  Bonus: This app is an MVC app!  (It was written on an earlier beta, so a few changes were required to get it to compile).

Here's what I did for my solution:

  • In the main body, I have a hidden field called "ContentBody" I use to hold the Encoded html (so that it doesn't render on the page).  I also put a TextArea called "PRBody" (that I will change to an fckeditor in javascript) and an insert button that calls a javascript function called InsertContent().
  • At the top of the page I include the files fckeditor.js and fckeditorapi.js
  • Also at the top of the page I have the following javascript between script tags:
window.onload = function() {
var oFCKeditor = new FCKeditor('PRBody');
oFCKeditor.BasePath = "/fckeditor/";
oFCKeditor.ToolbarSet = "CustomToolbar";
oFCKeditor.Height = 500;
oFCKeditor.Width = 450;
oFCKeditor.ReplaceTextarea();
}
function FCKeditor_OnComplete(editorInstance) {
editorInstance.InsertHtml("");
var sample = document.getElementById("ContentBody").value;
editorInstance.InsertHtml(sample);
}

What this does is first replace the TextArea with an fckeditor, thenonce the fckeditor is done loading, render the html inside the fckeditor.

FCKeditorAPI.GetInstance() will return undefined if the page hasn't finished loading yet.  That is why we have a function FCKeditor_OnComplete().  This event fires when the fckeditor loading has completed, allowing us to do, among other things, inject html like in my example.

I'm still having a bit of trouble with this on FireFox, but it works great on IE.  I'll be able to debug the FireFox issue a little later, but for now, it's bed time.

Happy coding!

Categories: ASP.NET | Javascript