我为我的页面引入了一串 html,并且我认为除了脚本标记之外它是 html 安全的。我知道三重大括号会转义 html,那么省略任何脚本标签的步骤是什么?
例子
var foo = "<h1>Foo</h1><script>some script that might possibly be in here</script><p>bar</p>
然后在我的 .hbs 中:
{{{foo}}}
我想查看 h1 和段落,但遗漏了脚本。
提前致谢。
您有几个选择:
在将脚本标签作为上下文传递到 Handlebars 模板之前,请删除脚本标签。
创建一个 Handlebars 帮助器来代替三重花括号表达式。像这样的东西:
Handlebars.registerHelper('strip-scripts', function(context) {
var html = context;
// context variable is the HTML you will pass into the helper
// Strip the script tags from the html, and return it as a Handlebars.SafeString
return new Handlebars.SafeString(html);
});
然后在您的模板中使用它,如下所示:
{{strip-scripts foo}}
使用帮助器时不需要使用三重花括号,因为您的帮助器已经返回一个 SafeString。
该帮助器可能比第一个选项更有用,因为您可以在整个模板中重复使用它。
查看此 StackOverflow 问题,以获取有关如何安全地剥离脚本标签的帮助:使用 JS 正则表达式从 html 中删除所有脚本标签 https://stackoverflow.com/questions/6659351/removing-all-script-tags-from-html-with-js-regular-expression
如果您使用 Node.js 在服务器端执行此操作,则可以使用 Cheerio 之类的东西来代替 jQuery。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)