How do I set content in TinyMCE 4, preferably within the $(document).ready(); block?

高科技黑手 picture 高科技黑手 · Dec 5, 2013 · Viewed 28.7k times · Source

As the title says, I've looked up the official documentation but it ain't working; here's my JavaScript (utilizing jQuery) code:

$(document).ready(function() {
    tinymce.init({
        element_format: "html",
        schema: "html4",
        menubar: false,
        plugins: 'preview textcolor link code',
        selector: 'TEXTAREA#rtf',
        toolbar: 'preview | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | blockquote subscript superscript | code'
    });
    tinymce.activeEditor.setContent($('TEXTAREA#rtf').text());
});
  1. I've tried to inspect tinymce and tinyMCE (got this from Googling) instances, and they both are objects alright.
  2. I've also tried to inspect tinymce.activeEditor and tinyMCE.activeEditor, but they turn out to be null!

(Cough) Somehow, after I restored everything back to where I started now it works:

$(document).ready(function() {
    tinymce.init({
        element_format: "html",
        menubar: false,
        plugins: 'preview textcolor link code',
        schema: "html4",
        selector: 'TEXTAREA#rtf',
        toolbar: 'preview | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | blockquote subscript superscript | code'
    });
});

I suspect it was due to either the UA cache or the XSLT transformed result cache that made the issue; thanks again for your time!

Answer

Radomír Laučík picture Radomír Laučík · Aug 31, 2016

I have found better solution that works anywhere in code (and is not a hack, unlike the setTimeout trick)

tinymce.get('tinymce-element-id').on('init',function(e) {
      e.target.setContent('my custom content');
});