IE下使用location對象有時會出現“沒有權限”的錯誤

發生錯誤都是一個原因:沒有權限(Permission denied)。從網上查了一下,沒有權限實在是一個太常見的提示,微軟自己都提供了很多更新來解決本不應該出現的“沒有權限”問題。很難講那些10%的用戶是沒有安裝哪個補丁導致的問題。

    PV代碼很簡單,如下:

    (function() {
    
    var a = [], n = document.createElement('script');
        a.push('url=' + encodeURIComponent(location.href));
        a.push('referrer=' + encodeURIComponent(document.referrer));
        n.src = '....pv.gif';
        document.getElementsByTagName('head')[0].appendChild(n);
    })();
    最有可能沒有權限的代碼就是location,因爲之前也遇到過跨域時使用location提示沒有權限的問題,因此縮小了範圍,把代碼改成了:
    (function() {
    
    var a = [], n = document.createElement('script');
        try {
            a.push('url=' + encodeURIComponent(location.href));
        } catch (e) {
            setTimeout(arguments.callee, 0);
            return;
        }
        a.push('referrer=' + encodeURIComponent(document.referrer));
        n.src = '....pv.gif';
        document.getElementsByTagName('head')[0].appendChild(n);
    })();
    這樣修改,數據正常了,問題解決了,但缺沒有合理的解釋,爲啥這樣使用location會提示沒有權限。可能我們的代碼有些特殊,上面這段js是放在一個script標籤上,這個標籤的最開始還有一段別的代碼(當然也很簡單),其中會設置一下document.domain,但是設置的document.domain就是當前的這個域,而且這個標籤放在head標籤的最開始,沒有什麼iframe和 script標籤,因此也不會出現多重設置域的問題,理論上也不會出錯。現在的整個片段是這樣的:
<head>
<script type="text/javascript">
    document.domain = 'bai.sohu.com';
    ...  //  簡單代碼

    (function() {
    
    var a = [], n = document.createElement('script');
        try {
            a.push('url=' + encodeURIComponent(location.href));
        } catch (e) {
            setTimeout(arguments.callee, 0);
            return;
        }
        a.push('referrer=' + encodeURIComponent(document.referrer));
        n.src = '....pv.gif';
        document.getElementsByTagName('head')[0].appendChild(n);
    })();
</script>

    這是啥問題?只能說這是ie的bug,成因爲:
    1. 代碼都在一個script中,並且在一個隊列中執行
    2. 之前會設置document.domain,並且等於當前的域
    3. 後面的代碼會使用location對象
    如果具備這些條件,那在某些ie下,會報“沒有權限”的錯誤。

    有兩個解決方法:
    1. 使用location時進行try catch,如果發現是沒有權限的問題,可以把代碼放到下一個執行隊列中(setTimeout)

    2. 直接放到兩個獨立的script標籤上,一個上設置document.domain,一個是使用location,這樣應該也能解決(是根據上面的理論得出,沒有經過測試


http://jadyyang.blog.sohu.com/145340845.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章