TinyMCE 初始化后无法获取编辑器内容怎么办?

恩豪 阅读 20

我在 Vue 项目里引入了 TinyMCE,初始化看起来没问题,但调用 tinymce.activeEditor.getContent() 时总是返回空字符串或者报错说 activeEditor 是 null,这到底是啥情况?

我试过在 setup 回调里获取,也试过加 setTimeout 延迟执行,都不行。下面是我的初始化代码:

tinymce.init({
  selector: '#my-editor',
  setup: (editor) => {
    editor.on('init', () => {
      console.log('Editor initialized');
      // 这里想立刻获取内容,但失败了
    });
  }
});
我来解答 赞 1 收藏
二维码
手机扫码查看
2 条解答
IT人浚博
问题在于你用的是 tinymce.activeEditor,这玩意儿在编辑器还没完全ready或者有多个实例的时候根本靠不住。

在 setup 回调里,editor 参数就是当前编辑器实例,直接用它就行:

let editorInstance = null;

tinymce.init({
selector: '#my-editor',
setup: (editor) => {
editorInstance = editor; // 先存下来

editor.on('init', () => {
// 这里用 editor.getContent(),别用 activeEditor
const content = editor.getContent();
console.log('内容:', content);
});
}
});

// 后续需要获取内容的地方,用保存的变量
function getContent() {
return editorInstance ? editorInstance.getContent() : '';
}


另外检查一下你的 selector #my-editor 对应的 DOM 元素是否真的存在,有很多情况是容器还没渲染出来就开始初始化了。

如果是在 Vue 里,更推荐把 editor 存到 ref 里,方便组件内任何地方调用:

const editorRef = ref(null);

onMounted(() => {
tinymce.init({
selector: '#my-editor',
setup: (editor) => {
editorRef.value = editor;
}
});
});

// 获取内容
const getEditorContent = () => editorRef.value?.getContent();


核心就一点:别依赖全局的 activeEditor,用你手里有的 editor 对象。
点赞
2026-03-13 08:28
东正
东正 Lv1
这个问题挺常见的,根源在于你对 TinyMCE 的初始化机制有点误解。

问题原因

你在 init 事件回调里用 tinymce.activeEditor.getContent() 是有问题的。setup 回调里的 editor 参数才是当前编辑器的实例,而 tinymce.activeEditor 是一个全局属性,指的是"当前激活的编辑器"。问题在于 init 事件触发时,这个全局的 activeEditor 可能还没被正确设置。

解决方案

在 setup 的 init 回调里,直接用传入的 editor 对象就行了:

tinymce.init({
selector: '#my-editor',
setup: (editor) => {
editor.on('init', () => {
// 这里直接用 editor,不要用 activeEditor
const content = editor.getContent();
console.log('编辑器内容:', content);

// 如果你想保存这个 editor 实例供其他地方使用
// 可以通过其他方式存起来,比如 store 或者 ref
});
}
});


如果你需要在组件其他地方获取内容

setup 回调里只能在这个闭包内访问 editor,外部拿不到。你需要把 editor 实例保存下来:

// 定义一个 ref 来存 editor 实例
const editorRef = ref(null);

onMounted(() => {
tinymce.init({
selector: '#my-editor',
setup: (editor) => {
// 保存到 ref 里
editorRef.value = editor;

editor.on('init', () => {
console.log('初始化完成');
});
}
});
});

// 在需要的地方调用
const getContent = () => {
if (editorRef.value) {
return editorRef.value.getContent();
}
return '';
};

// 组件销毁时清理
onUnmounted(() => {
if (editorRef.value) {
editorRef.value.destroy();
}
});


额外提醒

Vue 项目里还有个坑要注意:如果你的组件会被重复挂载(比如路由切换),一定要在 onUnmounted 或者 beforeUnmount 里调用 editor.destroy() 清理实例,否则下次初始化会出问题,activeEditor 也会指向错误的实例。

还有一种情况会导致 activeEditor 为 null:你的 selector 选中的元素不存在,或者初始化失败了。你可以在 init 的配置里加个 failed 回调检查一下:

tinymce.init({
selector: '#my-editor',
setup: (editor) => { /* ... */ },
init_instance_callback: (editor) => {
// 每次实例初始化完成后都会调用
console.log('实例已创建', editor);
}
});


总结一下:绝大多数情况下,不是 activeEditor 有问题,而是你应该在 init 事件里用回调参数里的 editor,或者把 editor 实例保存下来再调用。
点赞
2026-03-11 18:07