2014-12-03 37 views
5

我的目標是檢測廣告攔截器。我發現了幾個很好的例子,如FuckAdBlock如何使用Javascript處理err_blocked_by_client?

當廣告服務調用被阻止廣告攔截時,我們得到錯誤「err_blocked_by_client」。

我想處理這個錯誤,以下列方式:

var xhr = new XMLHttpRequest(); 
try 
{ 
xhr.open("GET","http://static.adzerk.net/ados.js", false); 
xhr.onreadystatechange = function (oEvent) { 
    if (xhr.readyState === 4) { 
     if (xhr.status === 200) { 
      console.log(xhr.responseText) 
     } else { 
      console.log("Error", xhr.statusText); 
     } 
    } 
}; 
xhr.send(); 
} 
catch(error) 
{ 
    console.log("ConsoleLog \n " + JSON.stringify(xhr)); 
    console.log("Error Catched" + error); 
} 

但在這種情況下,我不能夠識別catch塊上的錯誤原因。

請讓我知道更好的選擇來處理這個錯誤或我在這段代碼中的錯誤。

感謝

回答

3

你需要有你試試看的xhr變量之外。它在JSON.stringify(xhr)上失敗 - 因爲xhr超出了範圍。您需要使用onerror錯誤處理程序來處理異步XMLHttpRequest。您還需要從傳遞給onreadystatechange的函數中除去oEvent參數。見下:

var xhr = new XMLHttpRequest(); 

try 
{  
    xhr.open("GET","http://static.adzerk.net/ados.js", true); 

    xhr.onreadystatechange = function() { 
     if (xhr.readyState === 4) { 
      if (xhr.status === 200) { 
       console.log(xhr.responseText) 
      } else { 
       console.log("Error", xhr.statusText); 
      } 
     }    
    };  
    xhr.onerror = function(e) { 
     console.log("Error Catched" + e.error); 
    };  

    xhr.send();   
} 
catch(error) 
{ 
    console.log("ConsoleLog \n " + JSON.stringify(xhr)); 
    console.log("Error Catched" + error); 
} 
+0

對不起我寫錯了代碼的錯誤。我也是這樣做的。但它不起作用。沒有在日誌中我得到「err_blocked_by_client」。 – 2014-12-03 17:23:28

+0

@ManishPatwari好的,我看到了問題。你需要使用onerror處理程序 - 因爲它是一個異步調用。 – Donal 2014-12-03 17:29:00

+0

請給我代碼。我試過這個:xhr.onerror = function(error) { console.log(「on Error」); };但這也沒有奏效。 – 2014-12-03 17:41:04