【问题标题】:insert html without using innerHTML angular2插入html而不使用innerHTML angular2
【发布时间】:2017-03-20 13:04:13
【问题描述】:

使用 innerHTML 似乎不安全,还有另一种技术可以从数组中注入或插入 HTML?

假设我有一个包含 html 内容的数组,例如:

        const ItemSections: ItemSection[] = [
            {
                heading: "Lorem",
                SectionHTML: `
                    <h3>Lorem ipsum dolor sit amet</h3>
                    <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
                    <p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>,
                id: "Lorem"
            },
            {
                heading: "ipsum",
                SectionHTML: `
                    <h3>Ipsum amet</h3>
                    <p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>,
                id: "ipsum"
            }
        ];

组件模板

        <section class="row" *ngFor="let section of lItemSection">
                    <aside class="col-md-4 col-xs-12">
                        <h3>{{section.heading}}</h3>
                    </aside><!-- /col -->
                    <aside class="col-md-8 col-xs-12">
                         <p>{{section.SectionHTML}}</p>
                    </aside><!-- /col -->
        </section>

但是,上面的技术会渲染 html 标签

如果我使用 innerHTML 效果很好,例如:

                        <div [innerHTML]="section.SectionHTML"></div>

但会使应用面临 XSS 安全风险!

建议??

【问题讨论】:

  • 看起来您的 SectionHTML 来自某个服务调用的数据。确保在捕获这些数据时在将其保存到数据库之前对其进行正确验证。然后你就可以使用innerHTML了。
  • 目前是从实际组件调用,而不是从服务调用
  • 这意味着它在组件上是静态的。然后你可以轻松地使用我相信的 innerHTML。您的组件在客户端的任何方式。所以我觉得没关系。

标签: angular


【解决方案1】:

Angular 会清理使用 [innerHTML] 添加的 HTML。您需要使用DomSanitizer 以这种方式将潜在危险的内容放入 DOM。

另见

【讨论】:

    猜你喜欢
    • 2012-09-19
    • 2011-09-01
    • 2017-05-20
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多