问题
We intend to access another app url which is hosted on the same machine, but on different port. So my Angular 2 application http://localhost:8081/app/
is trying to open a site hosted on same server but different port i.e. localhost:9100
We are trying to access following url in an iframe
url = http://localhost:9100/custom/getCustomPage
<iframe id="customFrame" *ngIf="url !== null" frameborder="0" [src]="url"></iframe>
Error on Chrome/Firefox DOMException: Blocked a frame with origin "http://localhost:9100" from accessing a cross-origin frame. at http://localhost:9100/custom/getCustomPage Where Host:localhost:9100 Referer:http://localhost:8081/app/
I have added below headers to Response Filter:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, Content-Type
Access-Control-Allow-Methods:GET, POST, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers: content-length, Allow
Please help me identify a workaround so that iFrame allows to display the results.
This is currently working fine in IE 11.
回答1:
You have to return your URL as a trusted url using Dom sanitizer to bypass security. Here is what you can do:
In your html:
<iframe [src]='getSourceURL()'></iframe>
... and in your typescript:
import { DomSanitizer } from '@angular/platform-browser';
@Component({
....
})
export class YourComponent {
yourIFrameUrl: string;
constructor(public sanitizer: DomSanitizer) { }
getSourceURL() {
return this.sanitizer.bypassSecurityTrustUrl(this.yourIFrameUrl);
}
}
来源:https://stackoverflow.com/questions/47508270/cross-domain-issue-with-iframe-in-angular2