2012-10-25 79 views
1

我有以下代碼:的Internet Explorer - 檢查是否允許在Internet Explorer 8否認

if (window.opener != null && window.opener.foo != null) window.opener.foo = bar; 

有時候,window.opener設置。但是,如果用戶打開一個彈出窗口然後離開,應該避免嘗試在其上設置屬性。

在Firefox和Chrome,這個工作,因爲window.opener成爲空當用戶退出或刷新該窗口。在IE中,然而,window.opener不爲空,而window.opener.foo使「權限被拒絕」,而不是空。因此,window.opener.foo != null評估爲真。

如何解決這個問題,什麼樣的價值匹配「權限被拒絕」在Internet Explorer?

回答

1

這是我在IE8中使用的檢查:

if (window.opener && !window.opener.closed) { 
    // do what you will with window.opener 
} 

編輯:如果你想顯示一個友好的錯誤,你可以嘗試這樣的事:

try { 
    if (window.opener && window.opener.foo != null) { 
     window.opener.foo = bar; 
    } 
} catch (e) { 
    if (e.description.toLowerCase().indexOf('permission denied') !== -1) { 
     // handle it nicely 
    } else { 
     // some other problem, let it blow up 
     throw e; 
    } 
} 

這可以讓你明確處理「訪問被拒絕」錯誤,同時不隱藏任何其他潛在的錯誤。

+0

如果用戶如果用戶刷新頁面,則窗口關閉,因爲它應該是刷新頁面 –

+0

這@AndrewLatham不起作用。你想達到什麼目的? – jbabey

+0

在IE8中,對我來說,刷新導致它仍然在思考window.opener。關閉是錯誤的。我試圖訪問父頁面的一個屬性在彈出時顯示錯誤信息,如果權限被拒絕(這將是如果父頁面進行了改版或退出的情況下)。在Firefox/Chrome中,我可以通過檢查window.opener是否爲空來檢測。 –

0

如果您沒有訪問window.opener在IE的屬性,然後將它傳遞給Object.keys()將返回一個0長度的字符串。

用法示例:

if (window.opener && Object.keys(window.opener).length) { 
    // do what you will with window.opener 
}