How do I test an iframe and get all the response headers?

Viewed 1794

I am working on a webapp that can show url's in an iframe. But it also has the ability to first test the url before showing the url in an iframe. So before i show the iframe (set CSS rule to show the iframe element) i want to wait on the response. If i get an error or if i get a response header 'x-frame-options: DENY' i don't want to show the iframe and instead show an error message or something.

Consider this example:

const request = new XMLHttpRequest();
request.open("GET", urlToTest, true);
request.send();

Here i ALWAYS get a CORS issues. But this is expected, and testing this is not the same as what we actually want to do which is:

<iframe id="webiframe" "src"="urlToTest></iframe>

Then i tried the following:

this.webiframe is a reference of the <iframe>

this.webiframe.onload = function () {
    console.log('iframe ONLOAD');
}.bind(this);
this.webiframe.onerror = function () {
    console.log('iframe ONERROR');
}.bind(this);
this.webiframe.contentDocument.onreadystatechange = function () {
    this.iFrameEvent();
}.bind(this);
this.webiframe.contentDocument.addEventListener('DOMContentLoaded', this.iFrameEvent);
this.webiframe.contentDocument.addEventListener('load', this.iFrameEvent);
this.webiframe.contentDocument.addEventListener('onreadystatechange ', this.iFrameEvent);

But the event listeners that are added to the contentDocument are never called. The only event that is called is the onload event of the iframe reference.

So my question:

Is it possible to get some information/testing of iframe when setting a 'src' attribute on it. More specifically if the url is working and if not, why it's not working through response headers?

1 Answers

You should be able to access the webiframe.location.href attribute on the frame to get the URL. If you opened the frame you should already have this information. If the proper CORS headers are not in place you may not be able to get any details about the frame.

Frames are also accessible from the window.frames array if you are the parent. You can also try cross-document messaging as suggested in another StackOverflow answer.

NOTE: CORS is designed to explicitly block unauthorized cross-domain access in the browser. A server-based proxy solution may allow you to make a separate query and test the URL or collect information.

Related