How to get the position of an iframe relative to the viewport of the top window?
I have html:
<body>
[some stuff]
<iframe src="pageWithMyScript.html"></iframe>
[more stuff]
</body>
I want to find the location of an iframe relative to window.top (and / or top.document) from a script running inside an iframe. (Ideally, this would be without any frameworks, although I can always deconstruct how they do it, I suppose.)
+3
source to share
3 answers
This can only work if both the iframe and container share the same origin , otherwise CORS will need to be configured (you need access to both domains to do this)
/**
* Calculate the offset of the given iframe relative to the top window.
* - Walks up the iframe chain, checking the offset of each one till it reaches top
* - Only works with friendly iframes. https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Cross-origin_script_API_access
* - Takes into account scrolling, but comes up with a result relative to
* top iframe, regardless of being visibile withing intervening frames.
*
* @param window win the iframe we're interested in (e.g. window)
* @param object dims an object containing the offset so far:
* { left: [x], top: [y] }
* (optional - initializes with 0,0 if undefined)
* @return dims object above
*/
var computeFrameOffset = function(win, dims) {
// initialize our result variable
if (typeof dims === 'undefined') {
var dims = { top: 0, left: 0 };
}
// find our <iframe> tag within our parent window
var frames = win.parent.document.getElementsByTagName('iframe');
var frame;
var found = false;
for (var i=0, len=frames.length; i<len; i++) {
frame = frames[i];
if (frame.contentWindow == win) {
found = true;
break;
}
}
// add the offset & recur up the frame chain
if (found) {
var rect = frame.getBoundingClientRect();
dims.left += rect.left;
dims.top += rect.top;
if (win !== top) {
computeFrameOffset(win.parent, dims);
}
}
return dims;
};
+6
source to share
A bit easier:
function computeFrameOffset(win, dims ) {
dims = (typeof dims === 'undefined')?{ top: 0, left: 0}:dims;
if (win !== top) {
var rect = win.frameElement.getBoundingClientRect();
dims.left += rect.left;
dims.top += rect.top;
computeFrameOffset(win.parent, dims );
}
return dims;
};
+1
source to share
Small correction:
function computeFrameOffset(win, dims ) {
dims = (typeof dims === 'undefined')?{ top: 0, left: 0}:dims;
if (win !== top) {
var rect = win.frameElement.getBoundingClientRect();
dims.left += rect.left;
dims.top += rect.top;
dims = computeFrameOffset(win.parent, dims ); // recursion
}
return dims;
};
+1
source to share