如何在云端TinyMCE 7中保留html、body、head等默认移除的标签?
问题:TinyMCE 7 无法保留
<html>、<head>、<body>等根标签 我正在使用最新的云端托管版TinyMCE 7编辑器,需求是插入自定义HTML并能够修改包括<html>、<head>、<body>在内的所有标签。我尝试了如下配置,但TinyMCE仍会持续移除这些标签:
tinymce.init({ selector: '#mytextarea', plugins: 'advlist autolink lists link image charmap print preview hr anchor pagebreak code', toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code', menubar: false, // Disable HTML sanitation valid_elements: '*[*]', extended_valid_elements: '*[*]', verify_html: false, allow_html_in_named_anchor: true, // Allow all content, including style and script tags custom_elements: '*', schema: 'html5', // Optional: Disable automatic removal of elements allow_script_urls: true, allow_conditional_comments: true, allow_html_fragment: true, // Paste settings (optional but recommended) paste_allow_cleanup: false, paste_remove_styles_if_webkit: false, paste_remove_spans: false, });
附:我曾使用TinyMCE 5的fullpage插件实现该功能,但该插件现已被废弃,目前陷入困境。
解决方案
要让TinyMCE 7保留<html>、<head>、<body>这类根级标签,你需要调整配置,明确告诉编辑器要处理完整HTML文档而非仅body内容,以下是修正后的配置:
tinymce.init({ selector: '#mytextarea', plugins: 'advlist autolink lists link image charmap print preview hr anchor pagebreak code', toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code', menubar: false, // 核心:启用完整文档编辑模式 fullpage_default_html: '<html><head></head><body></body></html>', allow_full_html: true, remove_root_block: false, // 彻底关闭HTML内容过滤 valid_elements: '*[*]', extended_valid_elements: '*[*]', verify_html: false, custom_elements: '*', schema: 'html5', // 禁用粘贴时的自动清理 paste_allow_cleanup: false, paste_remove_styles_if_webkit: false, paste_remove_spans: false, // 其他保留的可选配置 allow_script_urls: true, allow_conditional_comments: true, allow_html_fragment: true });
关键配置说明:
fullpage_default_html:指定初始化时的完整HTML结构,让编辑器识别这是完整文档,而非仅body片段allow_full_html:明确允许编辑包含根标签的完整HTML内容remove_root_block: false:阻止编辑器自动移除<html>、<head>、<body>这类根级标签- 保留的过滤禁用配置(
valid_elements、verify_html等)确保所有标签和属性不会被自动清理
另外,建议通过代码视图(点击工具栏的code按钮)插入和修改完整HTML结构,避免可视化视图的自动格式调整干扰。
内容的提问来源于stack exchange,提问作者F0rc0sigan
相关产品推荐
相关产品推荐

