如何在TinyMCE 6中实现加载服务端内容的弹窗链接选择功能?
解决方案
1. 异步加载上传内容URL列表填充Selectbox
你需要先通过异步请求(比如fetch)从后端接口获取已上传内容的列表,将数据格式化为TinyMCE Selectbox要求的{text: 显示名称, value: 链接URL}结构后,再传入弹窗配置。
2. 提交时将高亮文本转为链接
在onSubmit回调中,获取用户选中的选项值,调用TinyMCE的内置方法,把选中的文本包裹成<a>标签。
完整修改后的代码
tinymce.init({ selector: '.course_page_editor', toolbar: 'custContentLink', setup: (editor) => { editor.ui.registry.addButton('custContentLink', { text: 'Insert Content Link', onAction: (_) => insert_content_link_dialog(editor) }); } }); async function insert_content_link_dialog(editor) { // 从后端接口获取已上传内容列表 let contentItems = []; try { const response = await fetch('/your-api-endpoint/get-uploaded-content'); // 替换为你的实际接口地址 const contentList = await response.json(); // 转换为Selectbox需要的格式 contentItems = contentList.map(item => ({ text: item.displayName || item.fileName, // 根据接口返回字段调整 value: item.url })); } catch (error) { console.error('加载内容列表失败:', error); // 加载失败时显示提示选项 contentItems = [{text: '加载失败,请重试', value: ''}]; } editor.windowManager.open({ title: 'Insert Content Link', body: { type: 'panel', items: [{ type: 'selectbox', name: 'content_list', label: 'Choose the file that the link should point to:', size: 5, items: contentItems, // 使用异步获取的列表 flex: true }] }, onSubmit: function (api) { const data = api.getData(); const selectedUrl = data.content_list; if (!selectedUrl) { api.close(); return; } // 获取选中文本,无选中则用文件名作为默认文本 const selectedText = editor.selection.getContent({format: 'text'}) || selectedUrl.split('/').pop(); // 插入链接 editor.execCommand('mceInsertLink', false, { href: selectedUrl, text: selectedText }); api.close(); }, buttons: [ { text: 'Close', type: 'cancel', onclick: 'close' }, { text: 'Add content link', type: 'submit', primary: true, enabled: contentItems.length > 0 && contentItems[0].value !== '' } ] }); };
关键说明
- 替换
/your-api-endpoint/get-uploaded-content为实际后端接口地址,接口需返回包含内容名称和URL的JSON数组,示例格式:[ {"displayName": "课程大纲.pdf", "url": "/uploads/course-outline.pdf"}, {"displayName": "实验指导书.docx", "url": "/uploads/lab-guide.docx"} ] - 提交逻辑中,若用户未选中文本,自动用URL的最后一段(文件名)作为链接文本;有选中内容则优先使用选中文本。
- 加载失败时会显示提示选项,并禁用提交按钮,避免无效操作。
内容的提问来源于stack exchange,提问作者pwesterbaan
相关产品推荐
相关产品推荐

