snippetjavascriptCritical
How to identify if a webpage is being loaded inside an iframe or directly into the browser window?
Viewed 0 times
webpagebrowserhowidentifybeingthedirectlyiframewindowloaded
Problem
I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?
Solution
Update (2024):
According to the docs on cross-origin script API access,
Previous Answer
Note: Browsers can block access to
Here's the working code:
According to the docs on cross-origin script API access,
window.self and window.top are both included in the list of properties that browsers of potentially-different origins can access.const inIframe = window.self !== window.top;Previous Answer
Note: Browsers can block access to
window.top due to same origin policy. IE bugs also take place.Here's the working code:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}top and self are both window objects (along with parent), so you're seeing if your window is the top window.Code Snippets
const inIframe = window.self !== window.top;function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}Context
Stack Overflow Q#326069, score: 1464
Revisions (0)
No revisions yet.