如何判斷 JavaScript 是否運行於 iframe?

2 分鐘閱讀

琳 avatar

js how to know if this script is running inside iframe or on the top most page?

Felo Search avatar
Felo Search

要判斷一段 JavaScript 腳本是否在 iframe 中運行,或者是否在最上層的頁面中,可以使用幾種方法。以下是一些常見的檢查方式:

檢查方法

  1. 使用 window.topwindow.self

    • window.top 代表最上層的窗口,而 window.self 代表當前窗口。如果這兩者不相等,則表示當前頁面在 iframe 中運行。
    function isInIframe() {
        return window.self !== window.top;
    }
    
  2. 使用 window.frameElement

    • window.frameElement 會返回當前窗口的 iframe 元素。如果返回值為 null,則表示當前頁面不在任何 iframe 中。
    function isInIframe() {
        return window.frameElement !== null;
    }
    
  3. 比較 document.referrer

    • 檢查 document.referrer 可以幫助判斷頁面是直接加載還是通過其他頁面(如 iframe)加載。如果 document.referrer 不為空,則可能表示頁面是在 iframe 中加載的。
    function isInIframe() {
        return document.referrer !== '';
    }
    

示例代碼

以下是一個綜合示例,展示如何使用上述方法來檢查當前頁面是否在 iframe 中運行:

function checkIframe() {
    if (window.self !== window.top) {
        console.log("這個頁面在 iframe 中運行");
    } else {
        console.log("這個頁面在最上層的頁面中運行");
    }
}

checkIframe();

這段代碼會在控制台輸出當前頁面的運行狀態。

結論

使用上述方法可以有效地判斷 JavaScript 腳本是否在 iframe 中運行或在最上層頁面中運行。根據具體需求,可以選擇最適合的檢查方式來實現功能。