Reputation: 121
I programmatically set the URL of an iframe within my web page. I must know which http requests are triggered from this URL change (URLs for CSS, scripts, images, etc. loading). I intercepted XMLHttpRequest, but this object is never called...
How can I intercept those http requests?
Is there another way to "load" an iframe and get all triggered URL requests?
Here is my code:
(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');
Upvotes: 5
Views: 19371
Reputation: 3641
It should be possible as described here as long as you can update the iframe code or if you can't, by injecting some code in the iframe at iframe load event as described here.
This typescript sorry might be translatable to javascipt ..
<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);
}
}
Upvotes: -1
Reputation: 75317
An <iframe />
has a different window
to the parent window, and as such, when you override XMLHttpRequest
, you're overriding the one in the parent window, not the one in the <iframe />
window.
Unfortunately, the same origin policy prevents you accessing the window
of the <iframe />
, so there is nothing you can do about this.
Even if the SOP wasn't in play here, whilst you could intercept AJAX requests, there'll be nothing you could do to intercept asset requests (CSS, JS, images).
Your best option is to use a proxy on your server, and route the iframe request through there; re-writing all asset URL's through your proxy instead of direct access (but even then you have impossible edge cases to track, such as JavaScript including other assets etc etc.
Upvotes: 4