greg84
greg84

Reputation: 7629

TinyMCE - Inserting content at cursor position in IE doesn't work

I'm trying to insert some content at the current cursor position or replace the selected content in a TinyMCE editor instance. I'm using this:

tinyMCEPopup.editor.selection.setContent(content);

Where content is a string of HTML that I want to insert.

It works great on Firefox, Opera and Chrome, but won't work in IE. Instead it inserts content at the beginning of the editor, instead of the selection. I've also tried:

tinyMCEPopup.execCommand('mceInsertContent', false, content);

Again, same behavior in IE. The TinyMCE code for inserting special characters uses the function above and that works! I've tried replicating it in my plugin and still no joy...

function insertChar(chr) {
    tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';');

    // Refocus in window
    if (tinyMCEPopup.isWindow)
        window.focus();

    tinyMCEPopup.editor.focus();
    tinyMCEPopup.close();
}

UPDATE:

Still not working in IE, Opera doesn't even show my plugin's button in the toolbar (although that's probably a separate issue)! I've now also tried the jQuery plugin, got the editors to load, but couldn't call the mceInsertContent method on it, even using this:

$('#my-editor-id').tinymce().execCommand('mceInsertContent', false, content);

Got an error: "object has no method: tinymce" - maybe I can't call that from a popup?!

Upvotes: 3

Views: 6953

Answers (3)

dadasign
dadasign

Reputation: 438

What has worked for me in a similar scenario, and what might be a solution here - use

editor.selection.getBookmark();

before loosing focus of the editor and

editor.selection.moveToBookmark();

before inserting the content.

The issue is that while in FF when you place the cursor at some spot in a text field containing text, then click elsewhere and return back (ie by hitting Tab) the caret will be displayed in the place where it was before focus was lost. In IE it will return to the beginning. I hope this helps.

Upvotes: 2

Terrence Tan
Terrence Tan

Reputation: 532

The problem is that TinyMCE loses the current cursor position when you click on something else like a button or link outside the editor, that causes it to lose focus.
To solve the problem, use the mousedown event of the button or link. In that way you can perform the insert action before the focus is lost.

$("#insert_link").mousedown(function (e) {
    var editor = tinyMCE.get("editor");
    editor.execCommand('mceInsertContent', false, "Insert Value");
    e.preventDefault();
});

Upvotes: 3

Katherine Unverdi
Katherine Unverdi

Reputation: 41

have you tried calling:

tinyMCEPopup.restoreSelection(); 

before calling

tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';');

Upvotes: 4

Related Questions