How to insert text into a tinyMce edtitor at the current position. It works perfect in Chrome, FF, Safari, but in IE it always starts at the top of the textarea. I currently do the following:
tinyMCE.execCommand('mceInsertContent',false, 'blabla this is tekst');
I tried with focus, other commands, nothing works :(.
Thanks for the help, but nothing worked. I found my own solution, and I felt like sharing this was needed, because I only found outdated solutions, that did not work :(.
The solution:
In your TinyMCE init add following code:
tinyMCE.init({
// General options
elements: elementid,
setup: function (ed) {
ed.onKeyUp.add(function (ed, e) {
actualCaretPositionBookmark = tinyMCE.activeEditor.selection.getBookmark();
});
ed.onClick.add(function (ed, e) {
actualCaretPositionBookmark = tinyMCE.activeEditor.selection.getBookmark();
});
}
Where "actualCaretPositionBookmark" is a global variable in javascript that can be accesed by all your javascript code
Then when you want to add text into your TinyMCE editor via javascript, add following code:
if (tinymce.isIE) {
tinyMCE.activeEditor.selection.moveToBookmark(actualCaretPositionBookmark);
tinyMCE.execCommand('mceInsertContent',false, 'My new text');
}else {
tinyMCE.execCommand('insertHTML',false, 'My new text');
}
You can use this approach to solve your issue. When initializing tinymce set the setup parameter to the following (inside tinyMCE.init({...})
...
theme: "advanced", // example param
plugins = 'code', // example param
setup : function(ed) {
ed.onInit.add(function(ed, evt) {
var dom = ed.dom;
var doc = ed.getDoc();
tinymce.dom.Event.add(doc, 'blur', function(e) {
// onBlur you save your caret position
actual_caret_position_bookmark = tinymce.get('your_editor_id').selection.getBookmark(2, true);
});
});
},
cleanup: true, // example param
...
now, you need to reset the tinymce caret position just before you insert the new content using the mceInsertContent command:
tinymce.get('your_editor_id').selection.moveToBookmark(actual_caret_position_bookmark);
If you have multiple editors in the same page you can try this
tinymce.get('content_id').execCommand('mceInsertContent', false, 'content to be inserted');
I have the same issue some while ago, I have a plugin using a modal popup and also use the same method described above. :
tinyMCE.execCommand('mceInsertContent',false, 'blabla this is tekst');
In IE9 the text is inserted in the top. The problem with playing with the caret is that, in my case, certain strange things happened (The backspace delete breaks), so I checked the code for the smileys plugin embedded inside the tinyMCE distribution that I'm using. the solution I found was to use the TinyMCEPopup object instead, like this:
tinyMCEPopup.execCommand('mceInsertContent', false, 'blabla this is tekst');
Regards.
来源:https://stackoverflow.com/questions/13849115/insert-text-at-current-position-tinymce-ie9