jQuery Load TinyMCE 4 On Demand - javascript

I am trying to use jQuery to load TinyMCE 4 on-demand from a CDN with no avail. I would like avoid loading TinyMCE when the page loads since it is a (relatively) bulky set of scripts, and instead I plan to trigger loading it when the user clicks a button. Here is what I have:
HTML:
...
<script src='//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js'></script>
...
jQuery:
...
if (typeof TinyMCE == 'undefined') {
$.getScript('//tinymce.cachefly.net/4/tinymce.min.js', function() {
alert('Loaded!');
tinymce.init({
selector: 'textarea',
plugins: [
'autolink contextmenu image link table'
],
menubar: false,
statusbar: false,
toolbar: false
});
});
}
...
I can see that jQuery does indeed fetch the script, as I can see the network activity in my inspector. The callback method is called, as I can see the Loaded! dialog appear, but TinyMCE dies not initialize. The JavaScript console does not show any errors.
Any idea on how I can get TinyMCE to initialize?
Thank you for your time.

Tinymce can not resolve baseURL when loading dinamically, so we have to hardcode it.
Add the following:
if (typeof tinymce == 'undefined') {
$.getScript('//tinymce.cachefly.net/4/tinymce.min.js', function () {
window.tinymce.dom.Event.domLoaded = true;
tinymce.baseURL = "//tinymce.cachefly.net/4";
tinymce.suffix = ".min";
tinymce.init({
selector: 'textarea',
plugins: ['autolink contextmenu image link table'],
menubar: false,
statusbar: false,
toolbar: false
});
});
}

change your code as following:
if (typeof tinymce == 'undefined') {
$.getScript('//tinymce.cachefly.net/4/tinymce.min.js', function () {
window.tinymce.dom.Event.domLoaded = true;
tinymce.init({
selector: 'textarea',
plugins: ['autolink contextmenu image link table'],
menubar: false,
statusbar: false,
toolbar: false
});
});
}
It is working for me.
more info https://stackoverflow.com/a/13361509/392526

Quote from original question:
Any idea on how I can get TinyMCE to initialize?
There is a problem with JQuery.getScript and tinyMCE, which I think is causing your trouble. It took me a day to figure it out, so I thought I should mention on it here.
$.getScript both adds and removes the script you're loading, executing it's content in the process. So, by the time your success function runs tinymce.init, the script tag no longer exists within your document.
tinymce.init on the other hand, looks through your document for that specific script tag in order to learn the base url to all its files. If it doesn't find it, it will get it from document.location instead.
I can't say what is the best way to solve this little problem. I found the following to do the trick for me (tinymce 4.2.7):
Open tinymce.min.js and search for the comment line ...
// Get base where the tinymce script is located
Look a few lines down where you'll find the statement ...
src = scripts[i].src;
... which should be altered to ...
src = "http://yourdomain.com/path/to/tinymce/tinymce.min.js";
I've identified the cause. But I'm not very happy with my solution. Maybe someone else will come up with a better one.

Related

TinyMCE 5 does not load existing content into editor, but the code is there in code view

I am upgrading TinyMCE to version 5.x and running into some compatibility issues. Whereas 4.x worked, I needed to change a few custom buttons is all and everything mostly works. If I add text to the editor and click save it works on one set of pages. On another page I can't seem to get the current contents into the editor, but the code view shows the code. If I then paste that code into a test site (fresh install tiny5) into the code view and save, it shows in the editor just fine.
I am using
formJson['DESCRIPTION'] = $('iframe').contents().find('body').html();
to populate the div - oh yes I am using a div as selector. In this case the editor acts like it is readonly with no contents showing.
and
$('.tox-edit-area').html($('iframe').contents().find('body').html()).show();
from within my TinyMCE init() function, which shows the contents in the editor, but they are readonly - or so it seems.
There are no errors showing in the console either.
Anyone have any pearls of wisdom to share? Thanks!
Update
// selector is passed into the function
var html = $(selector).html();//this is successful
tinymce.init({
selector: selector,
setup: function(editor) {
editor.setMode('design');
editor.setContent(html);//this does not load the code in design mode
alert(html);// this alerts the expected code
},
/// could any of this additional code below be causing an issue in tiny5?
invalid_styles: {
'*': 'font-size,font-family', // Global invalid styles
'a': 'background' // Link specific invalid styles
},
valid_styles: {
'*': 'border,font-size',
'div': 'width,height'
},
font_formats: 'Arial=arial, helvetica, sans-serif;',
toolbar: toolbtns,
plugins: 'code table lists',
//~ image_advtab: true,
menubar: false,
statusbar: false,
//~ force_p_newlines : false,
//~ force_br_newlines : true,
//~ forced_root_block : '',
width: '100%',
height: '500px',
relative_urls: false,
content_css: "/include/css/bootstrap.css",
images_dataimg_filter: function(img) {
return img.hasAttribute('internal-blob');
},
});
What am I doing wrong? :P
You're using a single selector to get the content to load and also as the target element for TinyMCE to replace. I can't reproduce your failure, but in your case setContent is unnecessary and removing this may resolve the issue. You don't need to manually set the content if the target element contains your content; TinyMCE will do that for you.
Here's an example using your code with setContent commented out:
http://fiddle.tinymce.com/QGgaab
If you are trying to load content into the editor I would do one of the following as they follow the design/API of the editor.
Load the content into the <div> or <textarea> before you init() the editor.
Use the setContent() API to load data into TinyMCE after TinyMCE has been initialized.
You appear to be relying on the underlying HTML structure that the editor uses to interact with the editor and (as you have seen) that is not guaranteed to remain the same over time.
Note: If you are updating the underlying element (<div> or <textarea>) after the editor is initialized TinyMCE won't see that update. It is hard to tell if that is part of the issue you have with content not reloading into the editor despite it existing in the underlying <div> or <textarea>.
I would also note TinyMCE has a readonly mode configuration option:
https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#setmode
...that you can use to enable or disable its readonly mode.

When using tinyMCE, is there a way to get a reference to the toolbar from an editor's instance?

I'm using tinymce, inline mode, and in certain cases I need the ability to show/hide the toolbar of the active editor using javascript.
It should be something like:
tinymce.activeEditor.getToolbar() // getToolbar doesn't exist
Only that given an editor instance, I couldn't find any way to get a reference to its toolbar.
Also note that there might be several toolbars on the page, but only one is displayed at any given time.
The toolbar is initialized like this:
tinymce.init({
selector: "#" + id,
menubar: false,
inline: true,
theme: "modern",
oninit: "setPlainText"
...
Thanks.
There is a discussion about this on the TinyMCE forum. It suggests:
...
setup: function (theEditor) {
theEditor.on('focus', function () {
$(this.contentAreaContainer.parentElement).find("div.mce-toolbar-grp").show();
});
theEditor.on('blur', function () {
$(this.contentAreaContainer.parentElement).find("div.mce-toolbar-grp").hide();
});
theEditor.on("init", function() {
$(this.contentAreaContainer.parentElement).find("div.mce-toolbar-grp").hide();
});
}
...

tinyMCE can no longer drag and drop images after upgrading from version 3 to version 4

My website was using the version 3 of tiny mce. One feature it had was that a user could drag an image into the editor, and it would automatically convert it to a base64 data-uri and insert it into the editor. I have just upgraded to version 4, and this functionality seems to be completely gone.
AFAIK, it was not a plugin or anything controlling this, just part of the default functionality, because I was still able to do it when initializing with minimal options, like this:
tinyMCE.init({mode: "none"});
tinyMCE.execCommand('mceAddControl', false, 'selector');
Was this feature removed from version 4, or is there a way to turn it back on?
I really want to upgrade to 4, but this is the only thing stopping me, as the image feature is crucial for my application.
Thanks!
If you want to enable the image drag & drop feature you have to do it explicitly with the code below.
tinymce.init({
...
paste_data_images: true
});
You have to add following property to enable drag and drop
tinymce.init({
selector: "#imgedit", // change this value according to your HTML
plugins: "paste",
menubar: "edit",
toolbar: "paste",
paste_data_images: true
});
and if you want to add drag and drop with insert url of image functionality then add below line of code
tinymce.init({
selector: "#imgedit", // change this value according to your HTML
toolbar: "image,paste",
plugins: "image,paste",
menubar: "insert,edit",
paste_data_images: true,
});

TinyMCE disable text input

I need to create an inline image editor using tinyMCE.
The basic principle has worked very well.
Wrap the image with an editable block level element.
Disable all buttons other than save and image.
Image augmented with a back end connected file manager.
The problem is the user can still type in the 'editable block level element'.
I need to ensure that this particular instance of the editor can only possibly be used to insert and edit a single image tag.
What is the most correct way of dealing with this?
EDIT -------------- Added code as suggested ---------------
Note that the following is just an tinyMCE init method that restricts the buttons and plugins. I am not sure that I can do what I want through the Init.
tinymce.init({
selector: ".CMS-image",
inline: true,
plugins: [
"save image filemanager"
],
inline: true,
toolbar: "image save",
menubar: false,
save_enablewhendirty: true,
save_onsavecallback: function () {
SaveCMSBlock(this.id)
}
});

TinyMCE textarea can't edit

Here is the problem. In my php submission page, I have a form with multiple fields including a textarea which is currently using TinyMCE and I also have an option for duplicating existing form. The thing is I can't edit the 2nd editor that was duplicated but the editor appear in textarea place. However I can edit and save 1st editor. I am not sure if its a bug or just me doing something wrong? I tried to update TinyMCE as well but didn't work.. any idea?
function initTinyMCE() {
tinyMCE.init({
mode : "textareas", //mode : "exact", elements : "mytextarea"
theme : "simple"
});
}
initTinyMCE();
$(document).ready( function(){
$('a#addmore').live('click', function(){
//*clone the existing form and inserting form here*
initTinyMCE();
});
$('a#toSubmit').live( 'click', function() {
tinyMCE.triggerSave();
$('.editwork-form').submit();
});
});
I can't seem to get .clone() to work, nothing in the debug console either. However, my working solution is as follows, maybe this helps?
initTinyMCE();
$("#append").live("click", function() {
var ta_count = $("textarea").length;
var elem = document.createElement("textarea");
$(elem).attr("id", ta_count.toString());
$(elem).appendTo("#ta_container");
initTinyMCE();
});
function initTinyMCE() {
tinyMCE.init({
mode: "textareas",
theme: "simple",
theme_advanced_path: false
});
}​
Instead of .clone()ing the element, I'm just creating a new textarea and appending it to the container (using the count of all textareas on the page as it's ID to make it unique), then re-calling the tinyMCE initialiser.
Example jsFiddle
Make sure your textareas have different ids, otherwise there won't be a second editor instance! This is a crucial thing when creating tinymce editor instances.

Categories