如何通过TinyMCE API获取用户选中的高亮文本?
Got it, let's sort out how to grab that highlighted text from TinyMCE correctly. You’re totally right about the quirks with getSel() returning an object instead of a string, and vanilla JS’s getSelection() can be finicky across browsers—sticking to TinyMCE’s built-in API is absolutely the smarter move here.
Here are two reliable, straightforward methods using TinyMCE’s own tools:
Method 1: Use getSelectedText() (Most Direct)
TinyMCE’s Selection API has a dedicated method for exactly this—getSelectedText()—which returns the plain text of the user’s selection as a string. No extra parsing needed.
Example code:
// Get a reference to your TinyMCE editor instance const editor = tinymce.get('your-editor-element-id'); // Grab the selected text const highlightedText = editor.selection.getSelectedText(); // Use it however you need console.log('User highlighted:', highlightedText);
Method 2: Use getContent() for Flexible Formatting
If you need more control (like ensuring you get pure text without any underlying HTML), you can use getContent() with the format option set to 'text'. This works just as well for grabbing selected text:
const highlightedText = editor.selection.getContent({ format: 'text' });
A Quick Note on getSel()
If you were curious about making getSel() work (though it’s not necessary here), you could extract the text from the returned DOM Selection object like this:
const selectionObj = editor.selection.getSel(); const highlightedText = selectionObj.toString();
But again, this is redundant when TinyMCE already gives you purpose-built methods to skip this step.
Just make sure you’re calling these methods after the editor has fully initialized—for example, inside a button click handler or the editor’s init callback—to avoid issues with uninitialized editor instances.
内容的提问来源于stack exchange,提问作者Adrian Vazquez

