警告:清理不安全的样式值 url

新手上路,请多包涵

我想在我的 Angular 2 应用程序的组件模板中设置 DIV 的背景图像。但是,我在控制台中不断收到以下警告,但没有得到预期的效果……我不确定动态 CSS 背景图像是否由于 Angular2 中的安全限制而被阻止,或者我的 HTML 模板是否损坏。

这是我在控制台中看到的警告(我已将 img url 更改为 /img/path/is/correct.png

警告:清理不安全的样式值 url(SafeValue 必须使用 [property]=binding: /img/path/is/correct.png (参见 http://g.co/ng/security#xss ))(参见 http:// g.co/ng/security#xss )。

问题是我确实使用 Angular2 中的 DomSanitizationService 来清理注入到我的模板中的内容。这是我在模板中的 HTML:

 <div>
    <div>
        <div class="header"
             *ngIf="image"
             [style.background-image]="'url(' + image + ')'">
        </div>

        <div class="zone">
            <div>
                <div>
                    <h1 [innerHTML]="header"></h1>
                </div>
                <div class="zone__content">
                    <p
                       *ngFor="let contentSegment of content"
                       [innerHTML]="contentSegment"></p>
                </div>
            </div>
        </div>
    </div>
</div>

这是组件…

 Import {
    DomSanitizationService,
    SafeHtml,
    SafeUrl,
    SafeStyle
} from '@angular/platform-browser';

@Component({
               selector: 'example',
               templateUrl: 'src/content/example.component.html'
           })
export class CardComponent implements OnChanges {

    public header:SafeHtml;
    public content:SafeHtml[];
    public image:SafeStyle;
    public isActive:boolean;
    public isExtended:boolean;

    constructor(private sanitization:DomSanitizationService) {
    }

    ngOnChanges():void {
        map(this.element, this);

        function map(element:Card, instance:CardComponent):void {
            if (element) {
                instance.header = instance.sanitization.bypassSecurityTrustHtml(element.header);

                instance.content = _.map(instance.element.content, (input:string):SafeHtml => {
                    return instance.sanitization.bypassSecurityTrustHtml(input);
                });

                if (element.image) {
                    /* Here is the problem... I have also used bypassSecurityTrustUrl */
                    instance.image = instance.sanitization.bypassSecurityTrustStyle(element.image);
                } else {
                    instance.image = null;
                }

            }
        }
    }
}

请注意,当我刚刚使用 [src]=“image” 绑定到模板时,例如:

 <div *ngIf="image">
    <img [src]="image">
</div>

并且 image 通过使用 bypassSecurityTrustUrl 一切似乎都运行良好……谁能看到我做错了什么?

原文由 Mark Sandman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 406
1 个回答

就我而言,我需要对多个组件进行消毒的功能。实现管道是解决这个问题的最合适和最优雅的方法。

执行:

 @Pipe({
  name: 'sanitizer'
})
export class SanitizerPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}

  transform(value: any, args?: any): any {
    return this.sanitizer.bypassSecurityTrustUrl(value);
  }
}

使用管道:

 <img [src]="pictureSrc | sanitizer" alt="selected picture">

原文由 teranshil 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进