If I have a site that holds an iframe:
<html>
<body>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<iframe src="http:/somelink.com/iframe.html"></iframe>
</body>
</html>
Is it then possible for the iframe to know if it can be "seen"? This for example by knowing the top position of the iframe related to the top of the screen.
This is my test iframe: (all values are 0, no matter scroll pos of parent)
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
console.log("ok");
check();
});
function check() {
// position of parent
var parentScrollTop = $(window.parent.document).scrollTop();
console.log("parentScrollTop: "+parentScrollTop);
// self position
var bodyPosition = $("body").position().top;
console.log("body position: "+bodyPosition);
setInterval(check, 1000);
}
</script>
<style type="text/css">
body {
background-color: red;
}
</style>
</head>
<body>
</body>
</html>
I made an image to be more clear.
I have to know from within the iframe if it's visible or not! So not from within the page that holds the iframe.
To check if iframe is loaded or it has a content with JavaScript, we can set the iframe's onload property to a function that runs when the iframe is loaded. document. querySelector("iframe").
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame> , <iframe> or <object> . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.
Inside an iframe, the visual viewport is the size of the inner width and height of the iframe, rather than the parent document. You can set any height and width on an iframe, but the whole document may not be visible.
I know this is an old question but some new API from Chrome have been released that could answer your question on the latest versions of Chrome (22+)
The InteractionObserver
you can find it here: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
There is a polyfill that is being developped (same repo) but it will not work from within the iframe afaik only if the script is on the parent webpage.
For other browsers their is some dark ways to do it based on timing attack, this article explains it pretty well: https://www.contextis.com/media/downloads/Pixel_Perfect_Timing_Attacks_with_HTML5_Whitepaper.pdf
Edit: Next Firefox version to come has the InteractionObserver
feature activated by default now, Same for Edge !
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