Cross domain issue with IFrame in Angular2

南笙酒味 提交于 2021-01-28 10:18:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!