如何将HTML作为字符串和绕过安全性传递



我想使用Ionic-Alert-Controller向用户显示一条消息。此消息是丰富的文本,可能包含链接,该警报实际上允许和工作,就像大多数链接的魅力一样。

但是(当链接是与另一个应用程序的深链接时)Angular有时会认为它们不安全,从而使链接变得难以置信。如何防止这种行为?该警报仅接受字符串作为消息,没有safehtml。

this.a : string = getRichTextFromServer();
// EXAMPLE
// this.a = `<a href="www.google.de">works like a charm</a>
// Hello Hello <b>Example Text</b>
// <a href="sd-viewer://testlink">UNSAFE LINK</a>
// `;
// Some links are marked as unsafe
this.alertCtrl.create({
      message: this.a
    });
    
    
// Doesn't compile as message is only allowed to be a string
this.alertCtrl.create({
      message: this.domSan.bypassSecurityTrustHTML(this.a)
    });
    
// Gives error that function must be used with property binding
this.alertCtrl.create({
      message: this.domSan.bypassSecurityTrustHTML(this.a).toString()
    });
    
// Some links are marked as unsafe again
this.alertCtrl.create({
      this.ds.sanitize(SecurityContext.HTML,
        this.ds.bypassSecurityTrustHtml(a)
      )
    });

我该怎么办?

编辑:HTML(在我的示例中存储在" A"中)是从后端动态加载的,因此在编译时不知道。因此,将其编辑以将RichText转换为运行时的Angular语法似乎很黑。

嗨,我昨天在这里回答:如何将对象绑定到iframe src

您可以创建管道并使用domsanitizer

喜欢这个

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(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
} 

然后将管道添加到应用模块

@NgModule({
   declarations : [
     ...
     SafePipe
   ],
})

在HTML中,您可以像这样使用它(URL是您的不安全URL)

<a href="{{url | safe}}">UNSAFE LINK</a>

如果有帮助,请标记我的答案是正确的,谢谢!

最新更新