Integrating Typekit into the Drupal CKEditor 3.x/WYSIWYG module

The ability to reference the site stylesheets in CKEditor on top of WYSIWYG in Drupal is very helpful in giving clients more context while editing content. One of the bigger problems I've run into though is, what if you're using Typekit to apply typefaces throughout the body text? It's not a huge discrepancy, but sometimes it can be kind of confusing, since the type kerning will render differently than what you're seeing in CKEditor.

After digging through the CKEditor docs for a bit I came across a little trick you can run while initializing the CKEditor object. Essentially you're just creating a <script> element on runtime while the CKEditor instance is being built in the <iframe>.

It's nothing crazy, but it took me long enough to track down the right location to put the code in, that I'm going to share it with you. Keep in mind this is a bit of a hack, not a patch. At some point I'd like to create a bonafide Drupal module to add this functionality. Also keep in mind since I'm working with the WYSIWYG module, this is for CKEditor 3.x. Support for 4.x with WYSIWYG is wonky at best at the time I'm writing this. I'm sure you can easily adapt this to 4.x though if it's necessary.

So, first you'd want to setup WYSIWYG CKEditor to reference your site CSS. You can do this by going to admin/config/content/wysiwyg/profile/{whatever filter you want}/edit. Head to the bottom and hit the "CSS" tab. You're going to both set the CSS path to your theme CSS, and then set "CSS Classes" to whatever selectors/classes you want available in the text/block styles dropdown. You don't have to do this but it makes it easier.

So, once you've got the site CSS referenced in the WYSIWYG CKEditor settings, you're going to want to hack the actual CKEditor JS that gets loaded when a new CKEditor instance is made. For Drupal 7/WYSIWYG/CKEditor 3.x this is wysiwyg/editors/js/ckeditor-3.0.js. You'd go to about line 47, and drop in this code:

settings.on = {    
instanceReady: function(ev) {      
var editor = ev.editor;       // Get a list of block, list and table tags from CKEditor's XHTML DTD.      
 
var dtd = CKEDITOR.dtd;      
var tags = CKEDITOR.tools.extend({}, dtd.$block, dtd.$listItem, dtd.$tableContent);             
 
// typekit      
var $script = document.createElement('script'),         
$editor_instance = CKEDITOR.instances[ev.editor.name];
      $script.src = '//use.typekit.com/{typekit-identifier}.js'; // you'll want to put in your own identifier here.
      $script.onload = function() {
         try{$editor_instance.window.$.Typekit.load();}catch(e){}
      };
$editor_instance.document.getHead().$.appendChild($script);

That's more or less it. You'll of course want to make sure you've got your own typekit identifier in there, where {typekit-identifier} is.

What you get is a more or less accurate representation of your type on your site, with the Typekit typefaces, to boot.