我如何拦截来自iframe的http请求

How can I intercept http requests from an iframe?

本文关键字:http 请求 iframe 何拦截      更新时间:2023-09-26

我在我的网页中设置了一个iframe的URL。我必须知道哪些http请求是从这个URL更改触发的(CSS,脚本,图像等加载的URL)。我截获了XMLHttpRequest,但是这个对象从来没有被调用过…

如何拦截这些http请求?

是否有其他方法来"加载"?一个iframe并获得所有触发的URL请求?

下面是我的代码:
(function(xhr){
  var pt = xhr.prototype;
  pt._open = pt.open;
  pt.open = function(){
   console.log('Open called...');
   this._open.apply(this, arguments);
})(XMLHttpRequest);
...
$('#iframe').attr('src', 'http://www.stackoverflow.com');

一个<iframe />与父窗口有不同的window,因此,当你覆盖XMLHttpRequest时,你覆盖了父窗口中的一个,而不是 <iframe />窗口中的一个。

不幸的是,同源策略阻止您访问<iframe />window,因此您对此无能为力。

即使SOP没有在这里发挥作用,当你可以拦截AJAX请求时,你将无法拦截资产请求(CSS, JS,图像)。

你最好的选择是在你的服务器上使用代理,并通过那里路由iframe请求;通过代理重写所有的资产URL,而不是直接访问(但即使这样你也有不可能跟踪的边缘情况,如JavaScript包括其他资产等)

这应该是可能的,只要你可以更新iframe代码,如果你不能,通过在iframe at iframe load事件中注入一些代码,如下所述。

这个typescript sorry可以翻译成javascript ..

<iframe [src]="iframeSiteUrl" title="myIframe" (load)="injectCustomHttpInterceptorHook() id="my-iframe" #iframeObj></iframe>

@ViewChild(iframeObj, {static: false}) iframeObj: ElementRef;
injectCustomHttpInterceptorHook (){
this.iframeWindow = (this.iframeObj.nativeElement.contentWindow || this.iframeObj.nativeElement.contentDocument);
    let xhrObj =this.iframeWindow.XMLHttpRequest.prototype.open;
    var parentObj = this;
    this.iframeWindow.XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
//intercepted here
        this.addEventListener('load', function() {
                console.log('load: ' + this.responseText);
        });
        xhrObj.apply(this, arguments);
        const oidcToken = JSON.parse(window.localStorage.getItem(parentObj.localstorageKey));
        const accessToken  = oidcToken.access_token;
        this.setRequestHeader('Authorization', "Bearer " + accessToken); 
    }
  }