加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在angular2中手动清理

发布时间:2020-12-17 07:55:18 所属栏目:安全 来源:网络整理
导读:我有一个textarea,用户将输入一些文本.文本不能是JavaScript或HTML等.我想手动清理数据并将其保存为字符串. 我无法弄清楚如何使用DomSanitizationService来“手动”清理我的数据. 如果我在页面上{{textare_text}},那么数据将被正确清理. 如何手动将其设置为
我有一个textarea,用户将输入一些文本.文本不能是JavaScript或HTML等.我想手动清理数据并将其保存为字符串.

我无法弄清楚如何使用DomSanitizationService来“手动”清理我的数据.

如果我在页面上{{textare_text}},那么数据将被正确清理.

如何手动将其设置为我拥有的字符串?

您可以按如下方式清理HTML:
import { Component,SecurityContext } from '@angular/core';
import { DomSanitizer,SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'my-app',template: `
  <div [innerHTML]="_htmlProperty"></div>
  `
})
export class AppComponent {

  _htmlProperty: string = 'AAA<input type="text" name="name">BBB';

  constructor(private _sanitizer: DomSanitizer){ }

  public get htmlProperty() : SafeHtml {
     return this._sanitizer.sanitize(SecurityContext.HTML,this._htmlProperty);
  }

}

Demo plunker here.

根据您的评论,您实际上想要逃避而不是消毒.

为此,check this plunker,where we have both escaping and sanitization.

import { Component,template: `Original,using interpolation (double curly braces):<b>
        <div>{{ _originalHtmlProperty }}</div> 
  </b><hr>Sanitized,used as innerHTML:<b>
        <div [innerHTML]="sanitizedHtmlProperty"></div>
  </b><hr>Escaped,used as innerHTML:<b>
      <div [innerHTML]="escapedHtmlProperty"></div>
  </b><hr>Escaped AND sanitized used as innerHTML:<b>
      <div [innerHTML]="escapedAndSanitizedHtmlProperty"></div>
  </b>`
})
export class AppComponent {
  _originalHtmlProperty: string = 'AAA<input type="text" name="name">BBB';
  constructor(private _sanitizer: DomSanitizer){ }

  public get sanitizedHtmlProperty() : SafeHtml {
     return this._sanitizer.sanitize(SecurityContext.HTML,this._originalHtmlProperty);
  }

  public get escapedHtmlProperty() : string {
     return this.escapeHtml(this._originalHtmlProperty);
  }

  public get escapedAndSanitizedHtmlProperty() : string {
     return this._sanitizer.sanitize(SecurityContext.HTML,this.escapeHtml(this._originalHtmlProperty));
  }

  escapeHtml(unsafe) {
    return unsafe.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")
                 .replace(/"/g,"&quot;").replace(/'/g,"&#039;");
  }
}

上面使用的HTML escaping function与angular code does相同的字符(不幸的是,它们的转义功能不公开,所以我们不能使用它).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读