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).
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.
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.
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.
How about
if ( self !== top ) { // you're in an iframe }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With