有没有办法查看 window.top 是否可以访问

Is there a way to see if window.top is accessible?

本文关键字:是否 访问 top window 有没有      更新时间:2023-09-26

>我有一个 iframe 尝试在父窗口中调用函数,如下所示:

window.top.updateIFrame(height);

显然,这仅在 iframe 和父窗口位置位于同一域中时才有效。因此,我想在尝试调用函数之前检查以确保 window.top 可访问。但我似乎无法做到这一点。

我尝试将 window.top 设置为一个对象,并且该对象存在,但是我想不出一种方法来查看访问是否被拒绝。

您可以使用 try/catch:

    function checkIfTopIsAccessible(){
        let windowVariable = null;
        try{
            windowVariable = top.window.document;
        }catch(e){
            // some log or even empty
        }
        return windowVariable;
    }
   
    if(checkIfTopIsAccessible() === null) return;

同样使用下面的函数,您可以尝试保存top.window引用:

    function getWindowReference(window) {
        /*
        window.frameElement === null in two cases:
            1. if the window isn't embedded into another document => window === top.window
            2. if the window is on a diffrent origin (from the top.window) => window of the safe iframe window
        so the window.frameElement has a value when it is embedded into another document on the same orgin => return top.window
        */
        if (window.frameElement === null) {
            return window;
        } else {
            return top.window;
        }
    }
    const windowVariable = getWindowReference(window);

尝试使用检查

if (typeof(window.top) == 'object' && typeof(window.top.updateIFrame) == 'function') 
   ...