Ash_and_Perl Ash_and_Perl - 2 months ago 17
HTML Question

Ckeditor 4 is removing the <img> tag if the HTML is not correct. How to stop this behaviour

we are using CKEditor in our project. We recently upgraded the version from 3.X to 4.x. After the update, we are not able to see

<img>
tags in the old saved documents. When we click on the source, we see

<p>&nbsp;<p>
in place of a
<p><img ......><p>
.

On further debugging, we found that many documents which had the
<img>
tag were also having a junk attribute in the
<img>
tag like
<img /="/" src="/folder/11801321/112267100.neck.png" height="308" width="467">
.

By junk, I mean this part of tag
/="/"
. This was a bug introduced while we were processing the user's input. We reverted old CKEditor version to 3.X and the editor was internally taking care of the junk values. it was trimming it off. so the users never complained.

But now the CKEditor 4 is not handling the HTML in the same way. It is actually stripping the whole
<img>
tag.

We have two options to fix this issue.
1. Remove the junk characters in all the documents. This is huge data. Needs approval from the user to do it.
2. Change CKEditor 4 config settings to get the same behavior as the CKEditor 3.X.

We are in favor of point 2. I have been searching and trying couple of config settings but haven't been able to nail it.

Let me know if any one has faced the same issue and have resolved it.

Answer

If you really want you can set all the code inside the img tag as "protected" and this way the editor will not strip this code:

CKEDITOR.config.protectedSource.push(/<img \/="\/" .*?>/g)
  1. Remember that your final html will not be valid.
  2. Since that part of the code is "protected" you will not see these images in the editor.

Here is a working example for that:
https://jsfiddle.net/oLb4Lmdb/

However - I really think it will be best to replace the string <img \/="\/" with <img in the source once the ckeditor instance is ready:

CKEDITOR.instances.editor1.on('instanceReady', function() {
    this.setData(this.getData().replace("<img /=\"/\"", "<img"))
})

This way you don't need to go over all the data in the "backround", and the replacement will be done "on the fly" for every document that you need to edit.

You can check this jsfiddle:
https://jsfiddle.net/k1ewc29p/