ionic2 url不安全问题 caused by: unsafe value used in a resource URL context

时间:2022-05-04 23:02:02

ionic2 中,img,iframe的src,a的href,有需要引入外部url的资源链接,但是,变量直接赋值url的话,会报错:

caused by: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)

顾名思义,加上看了官网文档:

http://http://g.co/ng/security#xss

明白了,是ionic2做了安全限制!

对应的html文件中是这样:

  <iframe class="all-iframe" [src]="srcUrl"></iframe>  

解决方法:

1.在对应ts文件中,导入DomSanitizer

import {DomSanitizer} from '@angular/platform-browser';

2.引用DomSanitizer

export class WebPage {
  srcUrl:any;
  constructor(private sanitizer: DomSanitizer) {
    this.srcUrl = this.sanitizer.bypassSecurityTrustResourceUrl(navParams.get('url'));
  }

注意:srcUrl类型为any,不能是string了