Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Check if content is sitting inside an iframe

Tags:

jquery

iframe

I'm loading a page through an iframe. If the content is sitting inside an iframe I need to add a loading spinner and if not, then no need for the spinner.

Problem: How can I use jQuery to check from within the content in the iframe if it's currently sitting in an iframe or not?

(i.e. it's simple to add jQuery to the page which loads the iframe itself, but I need the jQuery code to be in the file that's loaded inside the iframe).

like image 308
Allen S Avatar asked Aug 14 '13 12:08

Allen S


People also ask

How do you check if the page is loaded in iframe?

In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.

How do I check if an iframe is empty?

If you want to check if no page loaded inside iframe, and the iframe is not cross-domain you could check for the existence of the body tag inside of the iframe. If it exists, then something loaded. If the iframe is cross-domain, you will be blocked by the same-origin policy.

Can you access the content of an iframe?

The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.


1 Answers

How about

if ( self !== top ) { // you're in an iframe } 
like image 179
geekchic Avatar answered Sep 28 '22 01:09

geekchic