首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Javascript处理err_blocked_by_client?

如何使用Javascript处理err_blocked_by_client?
EN

Stack Overflow用户
提问于 2014-12-04 01:12:37
回答 1查看 5.9K关注 0票数 5

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

当广告服务调用被广告阻止时,我们会得到错误"err_blocked_by_client“。

我想通过以下方式处理这个错误:

代码语言:javascript
复制
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块上的错误原因。

请让我知道更好的选项来处理这个错误或我在这段代码中的错误。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2014-12-04 01:15:00

您需要在try之外使用xhr变量。它在JSON.stringify(xhr)上失败-因为xhr超出了范围。您需要使用onerror错误处理程序来处理异步XMLHttpRequest。您还需要从传递给onreadystatechange的函数中删除oEvent参数。如下所示:

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27277656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档