Often web developers and administrators need to check if their web pages are being loaded in web browser or iFrame. This is because it is possible that someone else is loading your web pages within iFrame and showing it as their own content on their domain. In this article, we will learn how to check if web page is loaded in IFrame or web browser. You can use it to stop people from displaying your content on their websites without your permission.
How to Check if Web Page is Loaded in IFrame or Web Browser
When your web pages are displayed in IFrame on another website, the origin (domain) of your web page becomes different from that of the IFrame. If your web page is displayed on an IFrame on same website, then the origin (domain) of both web page and IFrame are same. Web browsers can block access to window.top property due to same origin policy. Here’s a sample code for this purpose.
function inIframe () { try { return window.self !== window.top; } catch (e) { return true; } }
In the above code, both top and self are window objects and you are basically checking to see if your window is top window.
If the above code isn’t working for you, try using window.frameElement to check the same. It returns the element in which window is embedded.
window.frameElement ? 'embedded in iframe or object' : 'not embedded or cross-origin'
Alternatively, you can compare the window of web page with that of its parent (iframe). If they are different then the web page is an iframe.
if ( window !== window.parent ) { // The page is in an iframe } else { // The page is not in an iframe }
In this article, we have learnt several simple ways to check if a web page is loaded in an IFrame or web browser. You can use these checks to block your web pages from being displayed in an IFrame.
Also read:
How to Detect If Internet Connection is Offline in JS
How to Remove All Child Elements of DOM in JS
How to Check if Variable Exists or is Defined in JS
How to Convert UTC to Local Time in JS
How to Use Variable Number of Arguments in JS Function
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.