首页 > 解决方案 > 在 Angular/Karma/Jasmine 中测试 iframe 返回跨站点脚本错误

问题描述

我有一个带有 html 和 iframe 的 Angular(10) 组件。
无论我对 URL ( bypassSecurityTrustResourceUrl) 进行什么处理,都会出现跨站点脚本错误:

错误:资源 URL 上下文中使用了不安全的值(请参阅http://g.co/ng/security#xss

以下是我的代码的重要部分。

除了下面的代码,我还尝试过硬编码空字符串、有效的 html、null、# 等等。
我试过操纵我嘲笑的 DomSanitizer;包括将其关闭。
我已经验证了我的模拟被调用。

现在我猜是 Karma 使用了 iframe,然后我的代码使用了另一个/内部 iframe,并且某个地方 karma 的设置不允许在我的 iframe 中使用任何东西。

(让 Angular 不抱怨 iframe src/URL 的 xss 的唯一方法是在模板中对其进行硬编码。)


模板:

<iframe id="inlineFrameExample" [src]="embeddedLink">
</iframe>

.ts:

private url: string // Set elsewhere.

constructor(
  private sanitizer: DomSanitizer,
) { }

public get embeddedLink(): SafeResourceUrl {
  return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}

.ts.spec:

...
providers: [
  {
    provide: DomSanitizer,
    useValue: {
      bypassSecurityTrustResourceUrl: (val: string) => val,
    },
  },
...

标签: angulariframejasminekarma-runner

解决方案


它似乎工作得很好,使用包含所需所有内容的模块以不同方式导入它。

注意:工作示例

app.module.ts

import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";

@NgModule({
  imports: [],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

app.component.ts

import { Component } from "@angular/core";
import { DomSanitizer, SafeResourceUrl } from "@angular/platform-browser";

@Component({
  selector: "myapp",
  templateUrl: "app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  private url: string = "https://www.testUrl.com/";

  constructor(public sanitizer: DomSanitizer) {}

  public get embeddedLink(): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
  }

}

app.component.spec.ts

import { AppComponent } from "./app.component";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { AppModule } from "./app.module";

describe("iFrame tests", () => {
  let comp: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [AppModule],
      providers: [],
      declarations: []
    });
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should exist", () => {
    expect(comp).toBeTruthy();
  });
});

推荐阅读