CKEditor 3.x Youtube plugin

I've been working with CkEditor  for a while now. It is a pretty cool editor and makes it easy to compose and edit posts.

Recently I was working on modifying TEDxKhatoum website and I needed to embed a lot of Youtube videos into the website posts and articles. I am using CkEditor version 3 and I did not find a plugin to embed the youtube videos into the posts, and honestly I am too lazy to copy and paste the embed code from youtube. I read CkEditor documentation and found out that it is not so difficult to extend the editor's functionality. So I decided to create a simple plugin for CkEditor to embed the videos from youtube.

You can download the plugin if you are too lazy like me, I am going to explain how to create plugin anyway just coze I feel like doing it.

Creating CkEditor Plugin.

  • Okay let's start, first thing to do is to choose a name for your plugin :). I called my plugin zYouTube.
  • Seriously, first thing to do is to create a directory for the plugin inside the plugins directory fo CkEditor. Since I am calling my plugin zYouTube I created a directory called zyoutube inside CkEditor plugins directory
CKEDITOR_ROOT > plugins > zyoutube
  • Inside the newly created directory, create a new javascript file called plugin.js, this file will contain the source code of the plugin.
  • Add the following code to plugin.js
CKEDITOR.plugins.add( 'zyoutube',
{
	init: function( editor )
	{
	   //I will dump all the code here
	}
} );
  • Next thing is to define the components or the UI of the plugin. What I wanted is a dialog box with a text box where I can insert the Youtube video link, I added 2 more text fields for setting the video's width and height.
  • The way to do this is via Dialog and Editor Command. CkEditor plugins uses editor command to perform action associate with it.
  • I also needed to add a button to CkEdior toolbar to open the dialog. First I created new directory in zyoutube plugin directory called images and added a Youtube image icon to it.
CKEDITOR_ROOT > plugins > zyoutube > images
  •  Next defined a toolbar button on for my plugin, inside the init function I added the following code
CKEDITOR.plugins.add( 'zyoutube',
{
	init: function( editor )
	{
	   editor.ui.addButton('zYouTubeBtn',
              label: 'Add YouTube Video', //Label for the icon when people hover the mouse over it
              command: 'addYouTube',  //Command name, will be defined in next section
              icon: this.path + 'images/zyoutube.png' //Image Icone
          );
	}
} );
  • I defined the command and dialog inside the init function as follow
CKEDITOR.plugins.add( 'zyoutube',
{
	init: function( editor )
	{
           editor.ui.addButton('zYouTubeBtn',
              label: 'Add YouTube Video', //Label for the icon when people hover the mouse over it
              command: 'addYouTube',  //Command name, will be defined in next section
              icon: this.path + 'images/zyoutube.png' //Image Icone
          );

           //Command, open the addYouTube dialog
	   editor.addCommand( 'addYouTube', new CKEDITOR.dialogCommand( 'addYouTube' ) );

	}

         //The Dialog
	CKEDITOR.dialog.add( 'addYouTube', function( editor )
	{
           return{
               title: 'YouTube Video URL',  //Dialog title
               minWidth: 400,               // Dialog Minimum Width
               minHeight: 200,              // Dialog Minimum Height
              contents:
             [
                  id: 'general',
                  label: 'Settings',
                  elements:
                  [
                    //UI Elements
                  ]
             ]
          }//Return
 });

} );
  • If you test the above code it will show you an empty dialog box only. So we need to define the box elements
  • All the dialog elements will goes between the elements tags. I defined 4 elements, one elements is just an html to display some useless text and three text fields to allow user to input Youtube url,video width and height.
CKEDITOR.plugins.add( 'zyoutube',
{
	init: function( editor )
	{
           .
           .
         //The Dialog
	CKEDITOR.dialog.add( 'addYouTube', function( editor )
	{
           return{
               title: 'YouTube Video URL',  //Dialog title
               minWidth: 400,               // Dialog Minimum Width
               minHeight: 200,              // Dialog Minimum Height
              contents:
             [
                {
                  id: 'general',
                  label: 'Settings',
                  elements:
                  [
                    {
                      type: 'html', //Element Type
                      html: 'Paste Youtube Video Url in the text box' //Element contents 
                   },

                   { 
                     type: 'text', //YouTube Video URL Text Field 
                     id: 'contents', 
                     label: 'YouTube Link', 
                     required: true, 
                     validate: CKEDITOR.dialog.validate.notEmpty('Daaah, Where is the link!!!'),
                  },

                 { 
                    type: 'text', 
                    id: 'width', 
                    label: 'Frame Width', 
                    default: '560' 
                 }, 

                 { 
                   type: 'text', 
                   id: 'height', 
                   label: 'Frame Height',
                   default: '312' 
                } 
             ] 
          } 
       ]
    }//Return 
  });
});
  • Now if you run the above code you will get Dialog with 3 text fields

  • All whats left now is to define what happens when the Ok button is clicked. To do so we need to add a function to our init method called onOk.  This method will extract the video id from the YouTube URL and embed the video to your contents
onOk:function(){

      var videoLink = this.getContentElement('general','content').getInputElement().getValue(); //Get the URL from the text box
      var frameWidth = this.getContentElement('general','width').getInputElement().getValue();
      var frameHeight = this.getContentElement('general','height').getInputElement().getValue();

      //Regulare expression used to search for youtube video id            
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;

      var match = videoLink.match(regExp);

      if(match&match[7].length=11){
        //Valid YouTube link
        var videoId = match[7]; //Get Video id
        //Create Frame 
        var the_frame = '< iframe src="//www.youtube.com/embed/'+videoId+'" height="240" width="320" allowfullscreen="" frameborder="0">';

        //Insert to the contents
        editor.insertHtml( the_frame );
      }
      else{
       //Invalid Youtube link
       alert("hmmm, That is not a valid Youtube URL dude");
      } 
}
  • That's all. Now for all lazy people like you have a working plugin for embedding you-tube videos

zYouTube: A Youtube Plugin for CkEditor.

  • You can download the plugin from the download section at the end of this article.

 

zYouTube: Configuration

  • To configure the plugin, extract itnto CkEditor plugins directory
  • Enable the plugin by adding the following to CKEditor configuration config.js
config.extraPlugins = 'zyoutube';
  • Add the plugin button to CkEditor toobar.
//config.js Sample
CKEDITOR.editorConfig = function( config )

{

	config.toolbar_Full =

	[
            ....
            ....       

	    { name: 'colors', items : [ 'TextColor','BGColor' ] },

            { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','syntaxhighlight','zYouTubeBtn'] }

	];

	....
        ....

	config.extraPlugins = 'zyoutube';

};
  • Enjoy

Downloads

Title Downloaded Download
zYouTube 131 Download