Custom filebrowser callbacks in CKEditor 3.0

Last weekend I started playing around a little bit with the recently released CKEditor 3.0. I had wanted to have a WYSIWYG editor for my blog for quite a while now but was always either too lazy in general or just too lazy to write a custom uploader.Β  Last weekend was perfect for something like that, though, since I didn't receive a book and a DVD-box I had originally planed to spend the whole weekend on ;-)


The first part was naturally easy: Downloading it, placing all the right JS and CSS files on the server and writing some small JavaScript-embed code so that I can dynamically switch from Markdown and ReST (which I use normally for writing posts here) to HTML which automatically should then load the editor.

Then came the part I never found the motivation for before: Writing about 50 lines of code and about 200 lines of HTML and CSS to get the custom file uploader and browser to work. This part was also quite simple for CKEditor at first, but then reached a hurdle: What are the callback functions that actually tell the original upload dialog the URL of the file? The only official documentation I could find was about FCKEditor which used something like window.opener.SetUrl(yourUrl) when you select a file from the browser and probably a similar function when confirming the upload. Well, this doesn't work anymore with CKEditor 3.0.

The new version has a real callback system where the caller actually can determine the callback code. So the link that opens for instance the filebrowser or the upload-form's action includes an additional numeric parameter called "CKEditorFuncNum" that tells the callee a parameter to be used for window.opener.CKEDITOR.tools.callFunction.

So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum, url);

For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

<script type="text/javascript">
  window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum, 
    url, errorMessage);
</script>

If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

Something like this could perhaps be a little bit better documented :-)