Detect whether or not a page is allowed to load within an iframe

Is there a way to detect whether or not a page is allowed to load within an iframe?

If a URL can not load within an iframe, I would like to let the user know that the URL they are submitting will not work on our site.

I have tried to get the contents, but that doesn’t work:

1 Like

You’d have to query the page’s headers to see what their X-Frame-Options and Content-Security-Policy headers are. X-Frame-Options will contain DENY (nop), SAMEORIGIN (if you’re on the same domain), or ALLOW-FROM (which lets you define who can have access). Most pages will send SAMEORIGIN. ALLOW-FROM is only supported on Firefox in Android at present, and is not a standard response.

Content-Security-Policy is a bit more complex, but allows specification of different rules for different types of content; you could say that images can be used anywhere, but javascript cant, etc. It can define a frame-src to limit who can iframe their content.

2 Likes

This is not an assignment

1 Like

Is that possible with JS?
Also I am doing this because when you are not logged in on the domain the iframe says refused to connect. But after you log in on the domain the iframe works on my website.

1 Like

If you fetch the URL with javascript, you should be able to look at the response object’s headers to see what’s in it…

1 Like

Could you please show me an example of how to do it?
Because all the online answers say to use ajax which requires php.

1 Like

AJAX doesnt require php. AJAX stands for Asynchronous Javascript And XML.

There’s an example in the page i linked that shows you the Javascript…

1 Like

Ok thanks

1 Like

const myImage = document.querySelector(‘html’);

const myRequest = new Request(‘URL’);

fetch(myRequest).then((response) => {
// for each response header, log an array with header name as key
console.log(…response.headers);
response.blob().then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});
Doesnt seem to work

1 Like

It works but when the link does not allow it how do I detect that?
GET LINK net::ERR_FAILED 307
Like I want to detect if it has failed then redirect to login

1 Like

that doesnt feel right… a 307 isnt a failure, its a redirect…
it’s possible that’s the CORS handshake going awry, i suppose…

See where this comes out:

try {
  let response = await fetch(myRequest);
} catch (error) {
 console.log("Fetch Threw",error);
}
if(response?.ok) {
  console.log("Fetch Return");
} else { 
  console.log(`Fetch Response: ${response?.status}`);
}
1 Like

Thank you very much,
This still comes out with an error

const myImage = document.querySelector('img');

const myRequest = new Request('URL');

fetch(myRequest).then((response) => {
  // for each response header, log an array with header name as key
  console.log(...response.headers);
  response.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
});

try {
  let response = await fetch(myRequest);
} catch (error) {
 console.log("Fetch Threw",error);
}
if(response?.ok) {
  console.log("Fetch Return");
} else { 
  console.log(`Fetch Response: ${response?.status}`);
}

This is the code I am using.
The error comes out as

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at content.js:19:18)

By the way, this is for a chrome extension.
Thanks

To get around this error, you can either mark the script as a module:

<script type="module">
  ...
</script>

Or wrap everything in an IIFE which you mark as async:

(async () => {

})();

If you’re interested in why this is, you can read more here:

1 Like

Thank you very much,
The await error is now gone but now I get a new error.

Uncaught SyntaxError: Unexpected token 'try' (at content.js:27:1)

My code

const myImage = document.querySelector('img');

const myRequest = new Request('URL');

fetch(myRequest).then((response) => {
  // for each response header, log an array with header name as key
  console.log(...response.headers);
  response.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
});
(async () => 
try {
  let response = await fetch(myRequest);
} catch (error) {
 console.log("Fetch Threw",error);
}
if(response?.ok) {
  console.log("Fetch Return");
} else { 
  console.log(`Fetch Response: ${response?.status}`);
}
});

Many thanks

Sorry, there was a typo in my original reply (corrected now).

For the sake of getting it to work, put all of your code in the IIFE:

(async () => {
  const myImage = document.querySelector('img');
  const myRequest = new Request('URL');

  fetch(myRequest).then((response) => {
    // for each response header, log an array with header name as key
    console.log(...response.headers);
    response.blob().then((myBlob) => {
      const objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });
  });

  try {
    let response = await fetch(myRequest);
  } catch (error) {
   console.log("Fetch Threw",error);
  }
  if(response?.ok) {
    console.log("Fetch Return");
  } else { 
    console.log(`Fetch Response: ${response?.status}`);
  }
})();

Thanks

Uncaught (in promise) TypeError: Cannot set properties of null (setting 'src')
(async () => {
  const myImage = document.querySelector('img');
  const myRequest = new Request('LINK');

  fetch(myRequest).then((response) => {
    // for each response header, log an array with header name as key
    console.log(...response.headers);
    response.blob().then((myBlob) => {
      const objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });
  });

  try {
    let response = await fetch(myRequest);
  } catch (error) {
   console.log("Fetch Threw",error);
   console.log("Fetch Threw");
    document.getElementById('iframe').src = "link 1";
  }
  if(response?.ok) {
    console.log("Fetch Return");
    document.getElementById('iframe').src = "link 2";
  } else { 
    console.log(`Fetch Response: ${response?.status}`);
    console.log("oof");
  }
})();

This seems to be null

What did the log say before that error?

Not really sure what is null

It means that document.getElementById('iframe') returned null, i.e. there isn’t an element on the page with the ID “iframe”.

Compare:

document.querySelector('body');
// returns: <body> element

document.querySelector('element-does-not-exist');
// null