Date: 2020mar17
Update: 2025jul17
Language: javaScript
Q. Javascript: Detect if you are inside an <iframe>
A. Here's a function that does that:
function inIframe () {
try {
return window.self !== window.top;
} catch(ex) {
return true;
}
}
And here is a full html page to demo it:
<!DOCTYPE html>
<script>
// Check if the current document is in an iframe
function inIframe () {
try {
return window.self !== window.top;
} catch(ex) {
return true;
}
}
// Runs when the page loads
(function() {
if (inIframe()) {
console.log("Current document IS in an iframe");
}
else {
console.log("Current document is NOT in an iframe");
}
})();
</script>