How do I alter images being added via IMCE CKEditor plugin?

I just wanted to share my solution since I did not find any clue or different way of fixing the following problem:

Formerly, you could add a default class/ alter attributes of newly inserted images (or elements) in CKEditor. In Drupal 8, the ckeditor.config.js apparently was removed. Also, images added via IMCE CKEditor plugin are added via insertHTML and there seems not to be any way of manipulate the html string (despite listening to the insertHtml event) with the htmlParser.

How to alter the attributes of images added via imce in ckeditor?


So, here is what I did, even if maybe its dirty.

Add a new module which attaches a custom library to forms:

function mymodule_form_alter(&$form, $form_state) {
  $form['#attached']['library'][] = 'mymodule/form';

In the mymodule.libraries.yml:

  version: 1.x
    js/mymodule.js: {}
    - core/ckeditor
    - ckeditor/drupal.ckeditor
    - imce/drupal.imce
    - imce/drupal.imce.ckeditor

And in the mymodule.js I pretty much just re-write the imce sendto function:

if (undefined !== CKEDITOR && CKEDITOR.imce.sendto) {
  CKEDITOR.imce.sendto = function (File, win) {
    var imce = win.imce;
    var editor = CKEDITOR.instances[imce.getQuery('ck_id')];
    if (editor) {
      var i;
      var text;
      var lines = [];
      var selection = imce.getSelection();
      var is_img = imce.getQuery('type') === 'image';
      for (i in selection) {
        if (!imce.owns(selection, i)) {
        File = selection[i];
        // Image
        if (is_img && File.width) {
          lines.push('<img class="img-responsive" src="' + File.getUrl() + '" />');
        // Link
        else {
          // Use the selected text/image for the first link
          text = !lines.length && CKEDITOR.imce.getSelectedHtml(editor) || File.formatName();
          lines.push('<a href="' + File.getUrl() + '">' + text + '</a>');
      editor.insertHtml(lines.join('<br />'));

Hope this is helpful to somebody. And maybe there is another, better way of doing this - glad for any input!

Category: 8 Time: 2016-07-28 Views: 0
Tags: ckeditor imce

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.215 (s). 12 q(s)