You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过TinyMCE API获取用户选中的高亮文本?

Extract Highlighted Text from TinyMCE Using Its 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:58:32