In this short post, you'll learn how to detect AdBlock on your website and display the appropriate message to the user. It's quite straight forward but this method might be tricky if you are not familiar with javascript.
To achieve this create a method to checkAdBlocker and inside the method perform an ajax request to google tag manager which is essentially Google analytics script that you have placed on your website. Generally, Adblock block this script and other tracking scripts, so by doing so the ajax that perform the request will get blocked.
To achieve this create a method to checkAdBlocker and inside the method perform an ajax request to google tag manager which is essentially Google analytics script that you have placed on your website. Generally, Adblock block this script and other tracking scripts, so by doing so the ajax that perform the request will get blocked.
async function checkAdBlocker() { let isBlocked; async function tryRequest() { try { return fetch( new Request("https://www.googletagmanager.com/gtag/js?id=[GTag-Code]", { method: 'HEAD', mode: 'no-cors' })) .then(function(response) { // Google Ads request succeeded, so likely no ad blocker isBlocked = false; return isBlocked; }).catch(function(e) { // Request failed, likely due to ad blocker isBlocked = true; return isBlocked; }); } catch (error) { // fetch API error; possible fetch not supported (old browser) // Marking as a blocker since there was an error and so // we can prevent continued requests when this function is run console.log(error); isBlocked = true; return isBlocked; } } return isBlocked !== undefined ? isBlocked : await tryRequest(); } checkAdBlocker().then((isBlocked) => { if (isBlocked) { // ad block is on } else { // ad block is off } });
Leave a reply