My goal is to select an element regardless of where it is located inside a chain of nested iframes.
I am basically looking for a vanilla javascript equivalent of this: https://stackoverflow.com/a/11224815/1737287
I think you will not be able to search for an iframe within an iframe without changing the document's "context" using something like
iframe.contentDocument
method. You can read more about that here
In your case, you need to grab all of the iframes recursively as you reset the contentDocument as needed. Something similar to this may work for your purposes
function getAllIframes() {
let allIframes = [];
let topLevelIframes = document.getElementsByTagName('iframe');
for (let i = 0; i < topLevelIframes.length;i++) {
console.log(topLevelIframes[i])
traverseDeeperIntoIframes(topLevelIframes[i])
}
function traverseDeeperIntoIframes(ctx) {
allIframes.push(ctx)
// Fallback for contentWindow
const iframeContext = (ctx.contentDocument) ? ctx.contentDocument : ctx.contentWindow.document
const tmpFrames = iframeContext.getElementsByTagName('iframe')
console.log(iframeContext, tmpFrames)
for (let i = 0; i < tmpFrames.length;i++) {
traverseDeeperIntoIframes(tmpFrames[i])
}
}
return allIframes;
}
const allIframes = getAllIframes()
// Iterate over this allIframes <Array> resetting the contentWindow at every context.
// For example
function queryOverAllContentWindows(allIframes, cb) {
for (let i = 0; i < allIframes.length;i++) {
const ctx = (allIframes[i].contentDocument) ? allIframes[i].contentDocument : allIframes[i].contentWindow.document
// Pass the iframe context into any arbitrary callback
cb(ctx)
}
}