Detecting if there an element or iframe overlaid on top of my iframe
I have an iframe that can be embedded inside any website based on the content security policy.
Is there a way for the my iframe code to detect if there is an element or iframe laid on top of it to prevent clickjacking?
I tried using the trackVisibility in the IntersectionObserver v2 API for this purpose. Let us assume for now that we are good with the fact that support on Chrome is good enough.
For simplicity of discussion, let us assume that the threshold is set to 1.0, so that the entire iframe has to be visible for isVisible to be true. Also, let us call my iframe as iframeGood and the overlaid malicious iframe to be iframeBad.
If the opacity of iframeBad is set to anything higher than 0, then the isVisible of the IntersectionObserver API shows the value as false.
However, if the opacity of the iframeBad is set to 0, then the isVisible of the IntersectionObserver API shows the value as true. Maybe this is intended since iframeGood is fully visible in this case, but it does not solve of the problem of clickjacking.
So is there a way to detecting if there an element or iframe overlaid on top of my iframe from within my iframe?
3
This is not possible from the iframe, but if you where to supply your clients with some JS that loads your iframe, then this could also use the InteresectionObserver API to test if another page element intersects your iframe. However you would then have to apply it to every element on the page and most likely use the MutationObserver API to check for elements being added late to the page as well.
This can all be done without adding any real overhead to the parent page, as these are pretty low level API that don’t really effect page performance, so long as you use them in an intelligent way.
Code would look roughly something like this
function coverObserver(options) {
const onChange = options.onChange || (() => {})
const observerOptions = {
root: options.root,
rootMargin: '0px',
threshold: 0,
}
function callback(entries) {
onChange(entries.map((entry) => entry.target))
}
const observer = new IntersectionObserver(callback, observerOptions)
const observed = new WeakSet()
return function (nodeList) {
for (const node of nodeList) {
if (node.nodeType !== Node.ELEMENT_NODE || observed.has(node)) continue
observer.observe(node)
observed.add(node)
}
}
}
coverObsever({
root: myIframe,
onChange: (coveringNodeList) =>
console.log('Iframe covered by', ...coveringNodeList),
})(
document.querySelectorAll('* :not(iframe)')
)