Home >Web Front-end >JS Tutorial >Is My Webpage Loaded Directly or Inside an iFrame?
In web development, it may be necessary to determine whether a webpage is being loaded inside an iFrame or directly into the browser window. This distinction can have implications for the behavior and functionality of the webpage.
One method to identify this distinction is by comparing the window.self and window.top objects. In a webpage loaded directly into the browser window, these two objects will reference the same window object. However, when loaded within an iframe, window.self will reference the iframe window, while window.top will reference the parent window.
To check for this in a robust way, one can use the following code:
const inIframe = () => window.self !== window.top;
However, it's important to note that, despite being reliable in most browsers, this approach can be affected by cross-origin restrictions, especially in Internet Explorer. Therefore, it's essential to handle potential errors carefully.
Update (2024):
According to the documentation on cross-origin script API access, window.self and window.top are included in the permissible cross-origin properties. This suggests that the following code should provide a more consistent and reliable way to detect iFrames:
const inIframe = () => window.self !== window.top;
The above is the detailed content of Is My Webpage Loaded Directly or Inside an iFrame?. For more information, please follow other related articles on the PHP Chinese website!