wysihtml5编辑器iframe及部分HTML标签无法启用的原因咨询
解决wysihtml5编辑器无法启用iframe及部分HTML标签的问题
这个问题的核心原因是wysihtml5编辑器默认采用了严格的HTML标签白名单机制——它会自动过滤掉不在白名单内的标签,iframe和你提到的部分HTML标签正好不在默认允许的列表里。即使你开启了html编辑模式,编辑器依然会按照白名单规则清理内容,导致这些标签无法正常显示或保存。
下面是具体的解决步骤和修改后的代码示例:
1. 明确配置允许的标签和属性
你需要在初始化代码中添加allowedTags和allowedAttributes配置,把iframe和你需要的其他HTML标签加入白名单,同时指定这些标签允许使用的属性:
$(function () { $('.script_texteditor').wysihtml5({ "stylesheets": ["css/wysiwyg-color.css"], "color": true, "size": 'small', "html": true, "format-code" : true, "font-styles": true, "link": true, "font-type": true, "image":true, "fontFamilySelection": true, "emphasis": true, "lists": true, "blockquote": true, // 配置允许的标签,添加iframe和你需要的其他标签 "allowedTags": [ "p", "h1", "h2", "h3", "h4", "h5", "h6", "b", "i", "strong", "em", "strike", "u", "ol", "ul", "li", "blockquote", "code", "a", "img", "iframe" // 加入iframe标签 ], // 配置各标签允许的属性,添加iframe的相关属性 "allowedAttributes": { "a": ["href", "target", "title"], "img": ["src", "alt", "width", "height"], "iframe": ["src", "width", "height", "frameborder", "allowfullscreen"] // 允许iframe使用这些属性 }, "iframe": { "check_attributes": { "src": "url" // 验证src是否为合法URL } } }); });
2. 适配旧版本的wysihtml5(如果适用)
如果你使用的是较早版本的wysihtml5,可能需要用parserRules来配置标签规则,而不是allowedTags/allowedAttributes。示例如下:
$(function () { $('.script_texteditor').wysihtml5({ // 其他原有配置... "parserRules": { "tags": { "iframe": { "check_attributes": { "src": "url" }, "add_attributes": { "frameborder": "0" // 自动添加默认属性(可选) } }, // 保留其他默认标签的规则,或者按需添加 "p": {}, "a": { "check_attributes": { "href": "url" } } } } }); });
关键注意点
- 即使开启了
html编辑模式,wysihtml5依然会强制执行白名单规则,所以必须显式添加需要的标签。 - 确保你添加的属性符合编辑器的安全验证要求,比如
src属性会被验证为合法URL(对应你配置的"src": "url")。 - 如果你需要更多HTML标签,只需把它们加入
allowedTags数组即可,同时在allowedAttributes中配置对应的属性。
内容的提问来源于stack exchange,提问作者Ruchi Patel
相关产品推荐
相关产品推荐

