角度绕过SecuritySecurityTrustResourceUrl无法按预期工作

时间:2020-07-31 07:26:54

标签: angular angular-dom-sanitizer

我遇到了DomSanitizer.bypassSecurityTrustResourceUrl无法按预期工作的问题。

我已经创建了以下管道,可以在许多在线资源中找到它们:

import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';

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

  transform(url: string): SafeResourceUrl {
    var safeResource = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    return safeResource;
  }
} 

这应该创建一个SafeResourceUrl,它的属性“ changingThisBreaksApplicationSecurity”包含一个字符串。但是在我的情况下,该属性包含一个带有url属性的对象,该对象包含字符串。

预期结果: {"changingThisBreaksApplicationSecurity": "whatever the value of url is"}

我的结果: {"changingThisBreaksApplicationSecurity": { "url": "whatever the value of url is" }}

因此,将其设置为iframe的src时不起作用,因此,作为一种解决方法,我当前正在覆盖该值

safeResource["changingThisBreaksApplicationSecurity"] = safeResource["changingThisBreaksApplicationSecurity"].url;

这显然不是一个很好的解决方案,所以我希望其他人知道如何正确解决此问题。

1 个答案:

答案 0 :(得分:0)

听起来您只想要可以通过调用获得的 resourceUrl:

URL.createObjectURL(objectToCreateUrlFor);

这将为您提供对象的 URL。如果您想在 UI 中显示内容,那么您将使用安全管道来解析要在 UI 中绑定到的属性。注意:绑定的属性需要是 SafeUrl 类型

// .ts file
public safePipedContent: SafeUrl;

// use your pipe to set the value of safePipedContent
// use property binding to display your content
<iframe [src]="safePipedContent"></iframe>
相关问题