TinyMCE - Select text, alter text, update the editor and restore the selection

1.7k views Asked by At

I am working on a plugin for TinyMCE. The process should be like this:

1) The user selects some text

2) He presses a toolbar button of my custom plugin

3) A custom function is executed that does a custom action on the selected text, for example, lets say it surrounds the selected text with underline tags: <u></u>

4) After doing the action, the selected text is then inserted back inside the editor where the selection was made

5) Now, regardless of the selected text, I take ALL the editor's HTML and alter it according to my needs, such as adding a custom attribute to each tag in the HTML

6) Having the new HTML I want to insert it back into the editor

7) Moreover, the selected text should be still highlighted at the end of the process

I am struggling with steps 4-7.

My problems are divided in 2 steps:

A) I get the selected text and I can change it. The problem is I do not know how to set it back to the entire editor's text. In the plugin I do:

var newSelectionHTML = ed.selection.getContent();

But how can I update the selected part of the editor's text with newSelectionHTML

B) I do not know how to alter the whole editor's HTML and set it into the editor, while maintaining the user selection.

ed.setContent(newHTML)

Doing this removes the user selection and moves the cursor to the beginning. How can I save the user selection through the whole process (steps 1-7)?

Thank you in advance. Asaf

3

There are 3 answers

0
James Freund On BEST ANSWER

@jnoreiga's answer was very nearly the solution for me. Since tinymce seems to expecting an object with type Range it won't accept your plain object originalRange

I simply had to call getRng again, store that to a new variable and set that variable's properties with originalRange properties

var originalRange = jQuery.extend(true, {}, editor.selection.getRng());

/*
 * Do some logic,
 * Then set current range to originalRange
 */

var newRange = editor.selection.getRng();

newRange.startContainer = originalRange.startContainer;
newRange.startOffset = originalRange.startOffset;
newRange.startContainer = originalRange.endContainer;
newRange.startOffset = originalRange.endOffset;

editor.selection.setRng(newRange);
0
dfl On

Instead of jQuery.extend, just call the range's cloneRange method. The resulting range can be used directly in setRng.

1
jnoreiga On

store your range using cloning when the dialog first opens

originalRange = jQuery.extend(true, {}, editor.selection.getRng());

Then when you want to go back to the original selection

editor.selection.setRng(originalRange);