1

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?

1

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:

form:
  version: 1.x
  js:
    js/mymodule.js: {}
  dependencies:
    - 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)) {
          continue;
        }
        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 />'));
    }
    win.close();
  };
}

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.