【问题标题】:Cannot display images in [innerHTML]无法在 [innerHTML] 中显示图像
【发布时间】:2020-07-22 17:04:05
【问题描述】:

我的 Firebase 数据库的一个字段中存储了 HTML 数据,其中一些包含 <img src='[myImageUrl]'>。在我的 HTML 文件中显示该字段时,图像已被阻止,我在控制台中收到以下消息:

GET unsafe:[myImageUrl] net::ERR_UNKNOWN_URL_SCHEME

通过几天的研究(包括 stackoverflow 和独立的),我已经实现了一个管道(如下)来清理和绕过安全性,但是我仍然遇到同样的问题。有人可以阐明这个问题并为我指明解决方案的正确方向吗?

pub.html

<div [innerHTML]="((publication$ | async)?.body) | safeHtml "></div>

safeHtml.pipe.ts

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

@Pipe({name: 'safeHtml'})

export class SafeHtmlPipe implements PipeTransform {
  constructor( private domSanitizer: DomSanitizer) {}

  transform(
    value: any,
    context: SecurityContext = SecurityContext.HTML,
  ): SafeValue | null {
    return this.bypassSecurityTrust(context, this.domSanitizer.sanitize(context, value) );
  }

  private bypassSecurityTrust(
    context: SecurityContext,
    purifiedValue,
  ): SafeValue | null {
    switch (context) {
      case SecurityContext.HTML:
        return this.domSanitizer.bypassSecurityTrustHtml(purifiedValue);
      case SecurityContext.STYLE:
        return this.domSanitizer.bypassSecurityTrustStyle(purifiedValue);
      case SecurityContext.SCRIPT:
        return this.domSanitizer.bypassSecurityTrustScript(purifiedValue);
      case SecurityContext.URL:
        return this.domSanitizer.bypassSecurityTrustUrl(purifiedValue);
      case SecurityContext.RESOURCE_URL:
        return this.domSanitizer.bypassSecurityTrustResourceUrl(purifiedValue);
      default:
        return null;
    }
  }
}

*** 更新 *** 这似乎是 Firebase 存储的问题。在测试期间,我在 Firebase 上的单独实现中托管了相同的图像,并且图像显示没有任何问题。我已经确认每个实现的所有设置都是相同的。不知道为什么会这样,但看来我的代码不是问题。如果其他人遇到过这个问题,请告诉我。谢谢

【问题讨论】:

  • 你试过不使用safeHtml 管道吗?
  • @connorsFan - 我有,但是我有同样的问题。直接在 HTML 文件中显示图像时,没有问题。只有在使用 [innerHTML] 时才会出现此问题

标签: angular firebase innerhtml angular-dom-sanitizer


【解决方案1】:

经过几天的尝试,我终于解决了这个问题。不确定我是否会称其为像解决方案一样的适当解决方案。问题出在 [innerHTML] 呈现字段内容的方式上。在读取标签属性时,它会在属性值周围添加引号。

例如,如果您的字段包含 <img src="http://some-image.png">,[innerHTML] 将呈现 <img src=""http://some-image.png"">。请注意,重复引用是src 值。这会导致服务器抛出 403 Forbidden 错误,或者在某些情况下抛出不安全错误。

解决方法是简单地从值中删除引号,如下所示:<img src=http://some-image.png>。这适用于所有标签属性(src、class、id 等)。

这感觉很“hacky”,我很想找到一个真正的解决方案,但它确实有效,让我可以继续前进。我希望这对遇到同样问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 2019-09-24
    • 2012-06-16
    • 2021-02-28
    • 2020-02-19
    • 2018-08-02
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多