【发布时间】:2017-02-22 18:18:25
【问题描述】:
我想根据通过 http 调用服务获得的条件动态加载外部 JS 文件。
我想将<script> 插入app.component.html 为:
<script src="mysource/url"></script>
在我的组件中,我使用了 bypassSecurityTrustScript 和 bypassSecurityTrustHtml 都不适合我,我的脚本标签被删除了:
<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 谢谢,我会去看看。