Detect adblocker on your webapp

Here is the easy way you can detect an adblocker.

 const url = "https://www3.doubleclick.net";
 let isAdblockerEnabled = false;
  fetch(url, {
      method: "HEAD",
      mode: "no-cors",
      cache: "no-store",
    })
      .then(({ redirected }) => {
        if (redirected) isAdblockerEnabled = true;
      })
      .catch(() => {
        isAdblockerEnabled = true;
      });

fetch with HEAD Method: The code uses the fetch API with the HEAD method to request the headers of the URL without downloading the entire content. This request is sent to a URL that is commonly associated with ads (https://www3.doubleclick.net)

Request Options:

  • mode: "no-cors": This setting makes the request a no-CORS (Cross-Origin Resource Sharing) request, meaning the browser will restrict the types of headers that are accessible in the response.
  • cache: "no-store": This tells the browser not to cache the request, ensuring the request goes to the server every time.

Handling Redirects and Errors:

  • .then(({ redirected }) => {...}): The then block checks if the response was redirected. Some ad blockers may redirect requests to ad-related URLs to a different URL or block them entirely.
  • .catch(() => {...}): If the request fails (e.g., the ad blocker blocks the request or causes a network error), the catch block will be executed.

Setting Ad Blocker Detection:

isAdblockerEnabled = true: you can set the value to any variable or react state to get to know the final state of adblocker.