Home / Tutorials / How to detect adblock on your website?
How to detect adblock on your website? cover

How to detect adblock on your website?

Learn how to detect AdBlock on your website easily and determine what to show to the user afterwards

5 mins

707

3 years ago

0 comments

Expert

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.
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
    }
});
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this