【问题标题】:WARNING: sanitizing unsafe style value background-color警告:清理不安全的样式值背景颜色
【发布时间】:2023-03-23 05:11:01
【问题描述】:

使用 Angular,我从 Firebase 中提取数据。我希望用户的聊天消息基于用户选择的颜色item.color。对于使用蓝色的用户,我收到WARNING: sanitizing unsafe style value background-color:blue (see http://g.co/ng/security#xss).

我的 HTML:

<div *ngFor="let item of items; let i = index">
  <ion-card style="background-color:{{item.color}}" [ngClass]="{'me': item.sender == sender, 'notme': item.sender != sender}">
    <ion-card-header *ngIf="item.sender != sender">
      @{{item.sender}}
    </ion-card-header>
    <ion-card-content>
      {{item.message}}
    </ion-card-content>
  </ion-card>
</div>

我的 TS:

import { Component, OnInit, ViewChild } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html'
})
export class ChatPage{

  @ViewChild(Content) content: Content;

  user: {};
  style;

  ionViewDidLoad(){
    firebase.auth().onAuthStateChanged((user)=> {
      this.user = user;
      console.log('authState',user);
      if (user) {
        var uid = user.uid;
        firebase.database().ref('/userprofile/' + uid + '/' + 'chatcolor').once('value').then((snapshot)=> {
          this.color = (snapshot.val());
        });
      }
    });
  }


  constructor(public af: AngularFireDatabase, private Svc: Service, private sanitizer: DomSanitizer) {
    this.style = sanitizer.bypassSecurityTrustStyle("blue")
  }

}

我需要做什么才能做到这一点?

【问题讨论】:

  • 你试过ngStyle &lt;ion-card [ngStyle]="{ 'background-color': item.color }" [ngClass]="{'me': item.sender == sender, 'notme': item.sender != sender}"&gt;吗?

标签: angular typescript xss


【解决方案1】:

我也遇到了同样的问题。我已经用这个应答器解决了这个问题(感谢 Sape The Mape):

[ngStyle]="{'background-color': item.color}"

我想深入,我发现这篇关于 Angular 中的风格的好文章:dynamic styles 还有这个关于binding style的官方文档

希望对你也有帮助:)

【讨论】:

  • 谢谢!解决了与background-image 相同的问题:[ngStyle]="{'background-image': 'url('+object.image+')'}"
猜你喜欢
  • 1970-01-01
  • 2016-11-30
  • 2020-01-31
  • 2018-11-09
  • 2017-05-08
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
相关资源
最近更新 更多