Mohammed Noureldin
Mohammed Noureldin

Reputation: 16806

How to wrap TinyMCE element with custom HTML code without external JavaScript

I am trying to wrap some elements of TinyMCE with my custom HTML code.

For example, let us consider the user wants to add Media or Image element, the user will just click on Media or Image element icon, and he will be asked to enter the link, and TinyMCE will generate the required HTML code for that.

What I want to achieve is wrapping that generated HTML code with my custom code. I.e., so I will simply get this:

<div>
    ... What TinyMCE has generated for the image or media ...
</div>

For Media element, I tried using media_url_resolver, but that does not work for me, because this function does not give the ability to wrap the default behaviour, but only to rewrite the whole logic (which is a bad idea).

Could some one tell me if there is any TinyMCE native solution to get that (without any custom external JavaScript)?

Upvotes: 2

Views: 1890

Answers (1)

Michael Fromin
Michael Fromin

Reputation: 13726

There is no configuration option to do what you want but you can get notified when content is set into the editor and modify it before its inserted:

http://fiddle.tinymce.com/prgaab

The key code is here:

editor.on('BeforeSetContent', function (e) {
    //Look at this object - it tells you a bunch of stuff about the insert activity
    //such as was it via paste?  Was there selected content in TinyMCE that will be overwritten?  
    //Using the browser tooling you can inspect the e object and learn a lot about the content that will be set.
    console.log(e); 

    //Then you can modify that content if you want...for example:
    if (e.content.startsWith("<a href=")) {
        console.log('ADDING CONTENT');
        e.content = '<p>BEFORE</p>' + e.content + '<p>AFTER</p>';
    }
  });

Upvotes: 3

Related Questions