Forum Discussion

jacques_ca's avatar
6 years ago

TinyMCE - Add text in the editor

Hi

 

I tried to add some content in the text editor. It works, when I use the code below in the console, however when I use it in the component, it seems that the code is not executed.

tinymce.activeEditor.execCommand('mceInsertContent', false, " <p id='123'>bolded text</p> ");

$(tinymce.activeEditor.getBody()).one('click', function() {
  $(tinymce.activeEditor.getBody()).find('p').empty();
});

 Is there a sort of initialization or wrapper that I need to add?

  • jacques_ca or you just hook properly into the event lifecycle of TinyMCE =):

    	// runs when an editor instance is added to the EditorManager list
    	tinymce.on('addeditor', function(e) {
    		var editor = e.editor;
    
    		// wait for this particular editor instance to be initialized
    		editor.on('init', function(e) {
    			// when the editor is initialized, add the custom text
    			editor.execCommand('mceInsertContent', false, '<p id="123">bolded text</p>');
    		});
    	}, true);

    but of course you can also use the setTimeout() approach and hope for the best!

    • Thank you guys for your help -) sorry for the delay.

      lukI tried this method and I did not see any change. When I test the code in the console, I get this log: Dispatcher {fire: ƒ, on: ƒ, off: ƒ, once: ƒ, has: ƒ} and there is no result on the screen.

      TariqHussainI used windows.load() then settimeout waiting for 10s, I did not see any change.

      • luk's avatar
        luk
        Boss

        jacques_ca did you wrap that code into an IIFE? e.g.

        ;(function($) {
        	
        	// runs when an editor instance is added to the EditorManager list
        	tinymce.on('addeditor', function(e) {
        		var editor = e.editor;
        
        		// wait for this particular editor instance to be initialized
        		editor.on('init', function(e) {
        			// when the editor is initialized, add the custom text
        			editor.execCommand('mceInsertContent', false, '<p id="123">bolded text</p>');
        		});
        	}, true);
        })(LITHIUM.jQuery); // technically })(); is enough, no jQuery here...

        works for me here, I think if you do it via console, you're way too late in the javascript event lifecycle.

  • jacques_ca - it because your code is  working ieven before tinymce load. 

    You need to add settimeout so your code runs after sometime or check if tinymce is already being loaded using jQuery.