如何判斷頁面是在 iframe 裡面

  • 642
  • 0

因某些形況,某個頁面在 iframe 中時,需要執行某些任務,而不在 iframe 又需要執行另外任務,這樣的情況下,當然就要知道如何判斷網頁目前的狀態為何,下面提供三中方法

第一種

if (self != top) {
  alert('我在iframe中');
}

第二種

if (self.frameElement && self.frameElement.tagName == "IFRAME") {
  alert('我在iframe中');
}

第三種

if (window.frames.length != parent.frames.length) {
  alert('我在iframe中');
}