开发者

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

开发者 https://www.devze.com 2023-01-01 10:21 出处:网络
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 an开发者_开发百科d wont be inlin

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 an开发者_开发百科d 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


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


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.


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

Works fine! Credit goes to Greg

0

精彩评论

暂无评论...
验证码 换一张
取 消