【问题标题】:Angular 2 how to use script sanitizerAngular 2如何使用脚本消毒剂
【发布时间】:2017-02-22 18:18:25
【问题描述】:

我想根据通过 http 调用服务获得的条件动态加载外部 JS 文件。

我想将<script> 插入app.component.html 为:

<script src="mysource/url"></script>

在我的组件中,我使用了 bypassSecurityTrustScriptbypassSecurityTrustHtml 都不适合我,我的脚本标签被删除了:

  <div class='container-fluid'>
  <div class='row'>
    <div class='col-sm-12 body-content'>
      <div [innerHTML]="script"></div>
      <script type="text/javascript" [src] = "src"></script>
      <router-outlet></router-outlet>
    </div>
  </div>
</div>


   @Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public script: any;
  public src: any;
  public constructor(private titleService: Title, private sanitizer: DomSanitizer) {
    let x = '<script>alert("hi")</script>';
    this.script = sanitizer.bypassSecurityTrustHtml(x);
    this.src = sanitizer.bypassSecurityTrustScript('http://www.google.com');
  }

知道如何在这种情况下使用DomSanitizer 类吗?

【问题讨论】:

  • 你实现了吗?
  • @talentedandrew 不,我改变了我的方法。我正在使用 Angular Universal,我决定在 cshtml 视图中添加逻辑。
  • 好的,我也遇到了类似的问题。然后我使用了这个库 npmjs.com/package/postscribe ,这对我有用。在我的例子中,我在我的 angular v4 组件模板中渲染了一个第三方广告脚本。你一定要检查这个(库)。
  • @talentedandrew 谢谢,我会去看看。

标签: angular html-sanitizing


【解决方案1】:
this.src = sanitizer.bypassSecurityTrustResourceUrl('http://www.example.com');

http://www.example.com 是从中获取脚本的 URL。

【讨论】:

  • 这是否意味着我可以在 app.component.html 中使用&lt;script&gt; 标签?
  • 对,没想到。脚本标签将被清除。我稍后再看看。
  • &lt;script&gt; 标记在angular.io/docs/ts/latest/api/platform-browser/index/… 中作为bypassSecurityTrustResourceUrl 的示例被提及,但这似乎没有意义,因为脚本标记不能像您一样首先添加正确提到:D
  • 参见stackoverflow.com/questions/35570746/… 了解如何添加脚本标签。这样你就不需要消毒剂了。
  • 我完全同意你的看法。我这里没有什么复杂性。我有 Angular Universal,所以索引是在服务器端处理的。我尝试添加的 Javascript 不是模块化的。 Javascript 文件 url 由返回的 api 服务决定,例如用户是否存在、移动用户等
猜你喜欢
  • 2021-04-02
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
相关资源
最近更新 更多