Why sanitizer.bypassSecurityTrustStyle returns warning when setting [style.background-image] attribute?

孤人 提交于 2019-12-13 19:26:27

问题


I have a simple piece of code that won't work:

<div class="cover"
    [style.background-image]="sanitizer.bypassSecurityTrustStyle('url(/assets/img/picture (1).jpg)')">
</div>

The sanitizer.bypassSecurityTrustStyle returns the following message:

SafeValue must use [property]=binding: url(/assets/img/picture (1).jpg) (see http://g.co/ng/security#xss)

Also tried to move sanitization to a custom pipe, the result is the same.

When trying the following solutions Angular ignores style.background-image completely:

  1. [style.background-image]="'url(' + photo + ')'"
  2. [ngStyle]="{'background-image': 'url(' + photo + ')'}"

Why?

Angular: 5.2.4


回答1:


The problem occurs when you have an image url with spaces in it and the string, which is passed to css url() is without quotes:

[style.background-image]="'url(' + photo + ')'"

The code above works fine when your url has no spaces. If there are spaces just wrap actual image url with single quotes:

[style.background-image]="'url(\'' + photo + '\')'"

By the way, if this still does not work, try disabling Angular's built-in sanitization for the value passed in:

bypassSecurityTrustStyle(style)

You can create a pipe for that:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(
    private sanitizer: DomSanitizer
  ) { }

  transform(style) {
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }
}


来源:https://stackoverflow.com/questions/49419662/why-sanitizer-bypasssecuritytruststyle-returns-warning-when-setting-style-backg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!