Javascript:从弹出窗口中查找主页上的框架?

时间:2010-11-05 16:15:32

标签: javascript asp.net frames

在下面的Javascript中我必须继续从Popup页面中找到mainFrame,有没有更好的方法呢?

function sendRefreshMessage(data) {
    var myObj = null;
    myObj = document.getElementById('slPlugin');
    if (null != myObj) {
        try {
            //perform operation on myObj
        } catch (err) {
        }
    }
    else {
        if (null != top.opener.top.mainFrame) {
            myObj = top.opener.top.mainFrame.document.getElementById('slPlugin');
            if (null != myObj) {
                try {
                    //perform operation on myObj
                } catch (err) {
                }
            }
        }
        else {
            myObj = top.opener.top.opener.top.mainFrame.document.getElementById('slPlugin');
            if (null != myObj) {
                try {
                    //perform operation on myObj
                } catch (err) {
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

嗯,假设你的插件总是位于一个名为mainFrame的元素中,那么有一种更清洁(但不一定是更好的)的方法,这样做:

function findPlugin(container)
{
    var plugin = null;
    if (container.mainFrame != null) {
        plugin = container.mainFrame.document.getElementById('slPlugin');
    }
    if (plugin == null && container.opener != null) {
        plugin = findPlugin(container.opener.top);
    }
    return plugin;
}

function sendRefreshMessage(data)
{
    var plugin = findPlugin(window.top);
    if (plugin != null) {
        try {
            // Perform operation on `plugin`.
        } catch (err) {
            // Please avoid empty catch blocks, they're evil.
        }
    }
}