Search code examples
javascriptwidgetckeditormathjaxckeditor4.x

How to hide CKEditor widget content from source mode


I'm developing a new Widget for CKEditor 4 and some of its content is generated dynamically by a tool that parses CKEditor content window.

At first, the widget is simply a <span class="my-widget"></span> but then some content will be added on the fly.

When switching to CKEditor's source mode, then all the content inside span is visible and it gets really messy. Moreover, I don't want to save all that content in database but only the outer <span class="my-widget"></span>

I'm pretty sure this is feasible because this is how CKEditor's MathJax plugin works: when inserting a formula using TeX syntax, the plugin generates a <span class="math-tex">[formula here]</span>. Then, Mathjax runs and typesets the formula, producing the nice-looking LaTeX-like formula in CKEditor. However, when inspecting the code, it only shows the outer <span class="math-tex">[formula here]</span>.

I inspected their source code and I saw they were using an iframe inside the widget.

Can someone explain to me how it works and the way to do it without using an iframe if possible?

Thanks!


Solution

  • I actually achieved the desired result using the downcast property of a CKeditor widget. We can register a custom method that will be used to convert a widget into its text-based representation. Also, it is called both when switching from wysiwyg mode to source mode and when calling editor.getData().

    Also, reading the docs, you get that:

    The downcast function will be executed in the CKEDITOR.plugins.widget context

    meaning that this is pointing to your widget. So, essentially, I replaced all my widget's children by a single text node:

    downcast: function(element) {
      element.children = [new CKEDITOR.htmlParser.text(CKEDITOR.tools.htmlEncode(this.data.text))];
      return element;
    }
    

    And it does the trick!