Подтвердить что ты не робот

Вручную продезинфицировать строку

У меня есть textarea где пользователь будет набирать текст. Текст не может быть JavaScript или HTML и т.д. Я хочу вручную обработать данные и сохранить их в строку.

Я не могу понять, как использовать DomSanitizationService для ручной DomSanitizationService моих данных.

Если я сделаю {{ textare_text }} на странице, то данные будут правильно очищены.

Как мне сделать это вручную для string я имею?

4b9b3361

Ответ 1

Вы можете очистить HTML следующим образом:

import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: '
  <div [innerHTML]="_htmlProperty"></div>
  '
})
export class AppComponent {

  _htmlProperty: string = 'AAA<input type="text" name="name">BBB';

  constructor(private _sanitizer: DomSanitizer){ }

  public get htmlProperty() : SafeHtml {
     return this._sanitizer.sanitize(SecurityContext.HTML, this._htmlProperty);
  }

}

Демо плункер здесь.


Из ваших комментариев вы на самом деле хотите избежать дезинфекции.

Для этого проверьте этот поршень, где у нас есть и побег, и санитарная обработка.

import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: 'Original, using interpolation (double curly braces):<b>
        <div>{{ _originalHtmlProperty }}</div> 
  </b><hr>Sanitized, used as innerHTML:<b>
        <div [innerHTML]="sanitizedHtmlProperty"></div>
  </b><hr>Escaped, used as innerHTML:<b>
      <div [innerHTML]="escapedHtmlProperty"></div>
  </b><hr>Escaped AND sanitized used as innerHTML:<b>
      <div [innerHTML]="escapedAndSanitizedHtmlProperty"></div>
  </b>'
})
export class AppComponent {
  _originalHtmlProperty: string = 'AAA<input type="text" name="name">BBB';
  constructor(private _sanitizer: DomSanitizer){ }

  public get sanitizedHtmlProperty() : SafeHtml {
     return this._sanitizer.sanitize(SecurityContext.HTML, this._originalHtmlProperty);
  }

  public get escapedHtmlProperty() : string {
     return this.escapeHtml(this._originalHtmlProperty);
  }

  public get escapedAndSanitizedHtmlProperty() : string {
     return this._sanitizer.sanitize(SecurityContext.HTML, this.escapeHtml(this._originalHtmlProperty));
  }

  escapeHtml(unsafe) {
    return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
                 .replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  }
}

Используемая выше функция экранирования HTML экранирует те же символы, что и угловой код (к сожалению, их функция экранирования не является общедоступной, поэтому мы не можем ее использовать).

Ответ 2

В финале Angular вы можете использовать следующее:

  • Сначала импортируйте "DomSanitizer" из Angular платформы-браузера:

    import { DomSanitizer } from '@angular/platform-browser';
    import { SecurityContext } from '@angular/core';
    
  • Тогда в конструкторе:

    constructor(private _sanitizer: DomSanitizer){}
    
  • Затем используйте в своем классе:

    var title = "<script> alert('Hello')</script>"
    title = this._sanitizer.sanitize(SecurityContext.HTML, title);
    

Ответ 3

В angular ^ 2.3.1

Наличие представления с помощью контрольной панели bootstrap4. Смотрите, что в примере нам нужно значение для style.width.

<!-- View HTML-->
<div class="progress">
    <div class="progress-bar" role="progressbar" [style.width]="getProgress('style')" aria-valuenow="getProgress()" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Нам нужно дезинфицировать значение style.width. Нам нужно использовать DomSanitizer для дезинфекции значения и SecurityContext, чтобы указать контекст. В этом примере контекст стиль.

// note that we need to use SecurityContext and DomSanitizer
// SecurityContext.STYLE
import { Component, OnInit, Input } from '@angular/core';
import { SecurityContext} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';


@Component({
  selector: 'app-challenge-progress',
  templateUrl: './challenge-progress.component.html',
  styleUrls: ['./challenge-progress.component.sass']
})
export class ChallengeProgressComponent implements OnInit {

  @Input() data: any;

  constructor(private _sanitizer: DomSanitizer) { }

  ngOnInit() {
  }

  getProgress(type: string): any {
    if(type === 'style') {
      // here is the line you are looking for
      return this._sanitizer.sanitize(SecurityContext.STYLE,this._getProgress()+'%');
    }
    return this._getProgress();
  }

  private _getProgress():number {
    if(this.data) {
      return this.data.goal_total_current/this.data.goal*100;
    }
    return 0;
  }
}