Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the err_blocked_by_client using Javascript?

My aim is to detect the ad-blocker. I found couple of good examples like FuckAdBlock.

When the ad service call is blocked by the ad-blocked we get the error "err_blocked_by_client".

I want to handle this error, in the following way :

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);
}

But in this case i am not able to identify the error reason on catch block.

Please let me know the better option to handle this error or my mistake in this code.

Thanks

like image 314
Manish Patwari Avatar asked Oct 31 '22 13:10

Manish Patwari


1 Answers

You need to have the xhr variable outside of your try. It fails on JSON.stringify(xhr) - because xhr is out of scope. You need to use the onerror error handler to handle the async XMLHttpRequest. You also need to remove the oEvent parameter from the function passed to onreadystatechange. See below:

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);
}
like image 187
Donal Avatar answered Nov 14 '22 09:11

Donal