Mohammad
Mohammad

Reputation: 7418

Is there any clever way for Javascript to know its being executed in an iFrame?

I need the script to dynamically change how it functions if the page is embedded via an iFrame.

The script will be called in the iFrame source from a <script.. tag and wont be inline javascript.

Thank You in Advance!

Update: David provided this answer which works in Firefox and Chrome but doesn't work in IE8, any help with this is appreciated : )

if (window !== top) {
  alert('im in an frame');
}

Update2: Apparently this is a duplicate question, the right answer is:

if (top === self) { alert('parent'); } else { alert('iframe'); }

Credit goes to Greg

Upvotes: 4

Views: 187

Answers (3)

Mohammad
Mohammad

Reputation: 7418

if (top === self) { alert('parent'); } else { alert('iframe'); }  

Works fine! Credit goes to Greg

Upvotes: 0

Quentin
Quentin

Reputation: 943547

if (window != top) {
  // In a frame of some kind
}

Upvotes: 3

kennebec
kennebec

Reputation: 104770

IE does not return true for the equivalence operator (===) for two references to the same window object- even in a top level window, if(window===top) returns false.

But the simpler equality operator if(window==top) returns true in all the browsers if the object is the top window, and false if it is an iframe contained in a window.

Upvotes: 0

Related Questions