I have an Angular(10) component with html with an iframe.
Whatever I do with sanitizing the URL ( bypassSecurityTrustResourceUrl
) I get a cross site scripting error:
Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss )
Below is the important parts of my code.
Beside the code below I have tried hard coding empty string, valid html, null, # and whatnot.
I have tried manipulating my mocked DomSanitizer; including turning it off.
I have verified my mock is called.
Right now I guess it is Karma that uses an iframe and then my code uses another/inner iframe and somewhere karma's setup does not allow for anything in my iframe.
(The only way I get Angular to not complain about the xss the iframe src/URL is to hard code it in the template.)
Template:
<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,
},
},
...
It seems to work just fine, imported it differently with a module containing everything needed.
Note: Working 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();
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.