如何使用Javascript处理err_blocked_by_client?

时间:2014-12-03 17:12:37

标签: javascript jquery ajax adblock

我的目标是检测广告拦截器。我找到了几个很好的例子,比如FuckAdBlock

广告服务调用被广告拦截阻止后,我们会收到错误“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块的错误原因。

请告诉我更好的方法来处理此错误或我在此代码中的错误。

由于

1 个答案:

答案 0 :(得分: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);
}