Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CKEditor 4: How to add CSS stylesheet from plugin?

Tried this for now, but no luck

  editor.addCss(this.path + 'tabber.css');
  editor.document.appendStyleSheet(this.path + 'tabber.css');

Full code

(function () {
  CKEDITOR.plugins.add('tabber', {
    init: function (editor) {
      editor.ui.addButton('addTab', {
        command: 'addTab',
        icon: this.path + 'icons/tabber.png',
        label: Drupal.t('Insert tabs')
      });
      editor.addCss(this.path + 'tabber.css');
      editor.document.appendStyleSheet(this.path + 'tabber.css');
      editor.addCommand('addTab', {
        exec: function (editor) {
          editor.insertHtml('<dl>' +
            '<dt>Tab title 1</dt>' +
            '<dd><p>Tab content 1.</p></dd>' +
            '<dt>Tab title 2</dt>' +
            '<dd><p>Tab content 2.</p></dd>' +
            '</dl>');
        }
      });
    }
  });
})();

Solution (thanks for the answer for pointing the right way) inside init

  var cssPath = this.path + 'tabber.css';
  editor.on('instanceReady', function () {
    this.document.appendStyleSheet(cssPath);
  });
like image 582
SebCorbin Avatar asked Sep 13 '13 09:09

SebCorbin


3 Answers

CKEDITOR.addCss accepts string as a parameter, so there's no way to pass any path there. CKEDITOR.document.appendStyleSheet is correct though (fiddle):

CKEDITOR.replace( 'editor', {
    on: {
        instanceReady: function() {
            this.document.appendStyleSheet( 'http://path.to.your.css' );
        }
    }
} );

Just make sure that:

  1. Your CSS exists.
  2. It has correct permissions to be read.
  3. Your HTML is allowed in the editor (also read the integration guide as since 4.1 you need to adjust allowedContent for your command).

I guess you may also find CKEDITOR.getUrl useful.

like image 115
oleq Avatar answered Sep 18 '22 07:09

oleq


Add the following to config.js:

config.contentsCss = [CKEDITOR.getUrl( 'contents.css' ), '/path/to/your/css'];

This will append your CSS file to the default CKEditor styles. The advantage of this method over instanceReady is that (for me at least) when the user toggled modes from Source to Visual, the instanceReady event would not re-fire and custom styles would not be reapplied.

like image 27
Eric Corriel Avatar answered Sep 20 '22 07:09

Eric Corriel


If you are using CKEditor 4.4 or later, you can use

editor.addContentsCss( pluginDirectory + 'styles/example.css' );

If you are using CKEditor an older version like 4.3, you should use:

beforeInit: function(editor) {
        var ccss = CKEDITOR.config.contentsCss;
        if(typeof ccss == 'string'){
            ccss = [ccss];
        }
        ccss.push('/css/style.css');
        CKEDITOR.config.contentsCss = ccss;
    }

Take a look at this ticket when the feature was created: https://dev.ckeditor.com/ticket/11532

like image 21
Edwin Guilbert Avatar answered Sep 20 '22 07:09

Edwin Guilbert