How do I detect whether the document is in a frame or in an iframe?

Who is Participating?
COBOLdinosaurConnect With a Mentor Commented:
in the head of the page
<script type="text/javascript">
function testSelf()
   return (arr.length==0) ? 'iframe' : 'frame';

In the body tag of the framed page you fire it with:

<body onload="if (self != top) alert(testSelf());"

RedKelvinConnect With a Mentor Commented:
this will tell you if the document is in a frame
Samer ChidiacConnect With a Mentor Chief Innovation & Strategy OfficerCommented:
i'm not sure how you're going to use the information once you knew it ..

can you clarify why you want to know it...  ( like r you going to write a script to detect that and write an action to redirect users or something ? )

usually the framed page is a page that is formed from different pages assembled in together using frames, and the Main Framed Page is very simple can cannot include but frames (it even don't have a <Body> Tag) while the sub pages contains the Content .. while an iframe can be embedded in a normal page.. and can be floating..

Take Care,


Samer Chidiac
Microsoft MVP - ASP /
terminator_IIIConnect With a Mentor Commented:
Hi you can add this into the <body> tag of any page and it will take you to the correct page.  You can change the url of course.  This is fix is needed if a search engine arrives at a parentless page and you want to put the navigation back.

Look at the parent.frames.length aspect

<body topmargin="0" leftmargin="0" OnLoad="if(parent.frames.length==0)top.location='';">

Shout if you need more help on what to do after you redirect.

zhghlAuthor Commented:
if( top != self ){
     if( window.frameElement.tagName== "IFRAME" ){
      alert( "iframe" );      
      alert( "frame" );      
   alert( "page" );

thanks a lot
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.