Recently I had to determine when my code is running in an iframe. In order to do this many would simply use this code:


var isInIframe = window.top == window.self;

Unfortunately, if you are writing code that can potentially be added to any page (even those whose code isn’t fully controlled by you), you may experience an unexpected result when someone decides to write to window.self. Truthfully, it does seem strange to even write a variable called self in the global namespace, but at Monetate we have run into this issue before. For this reason, it may be a better idea to simplify the test even further by doing the following:


var isInIframe = window.top == window;

As far as I can tell, there isn’t a reason why this wouldn’t work, but perhaps you have found an instance in which this would fail. If so, please let me know, but as for now I think this simple solution should indicate whether or not the window is the top-most window. šŸ˜Ž

Categories: BlogJavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *