【问题标题】:Testing iframe in Angular / Karma/Jasmine returns cross site scripting error在 Angular/Karma/Jasmine 中测试 iframe 返回跨站点脚本错误
【发布时间】:2020-12-21 13:03:03
【问题描述】:

我有一个带有 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,
    },
  },
...

【问题讨论】:

    标签: angular iframe jasmine karma-runner


    【解决方案1】:

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

    注意:工作example

    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();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2018-01-31
      • 2018-04-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多