Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How To Detect ad-blocker Using Mutation Observer API ?
Next article icon

How To Detect ad-blocker Using Mutation Observer API ?

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Ad blockers are browser extensions or tools that prevent ads from displaying on web pages. While they provide a cleaner user experience, they can impact website revenue for publishers who rely on ad income.

Detecting ad blockers allows websites to request users to whitelist them or provide alternative monetization options. One effective way to detect ad blockers is by using the Mutation Observer API in JavaScript which gives the developers access to monitor changes in the DOM (Document Object Model).

Table of Content

  • Overview of Ad-Blocker Detection
  • What is Mutation Observer API?
    • Key features of Mutation Obserever API
  • How Ad-Blockers Affect DOM Elements?
  • Detecting DOM Modifications by Ad-Blockers

Overview of Ad-Blocker Detection

Ad-blockers have a function that blocks or removes elements associated with ads, such as <iframe>, <div>, and <script> tags. By using the Mutation Observer API, you can monitor these elements for removal or alteration and take appropriate action when such changes are detected.

What is Mutation Observer API?

The Mutation Observer API provides a way to asynchronously observe changes in the DOM tree. This includes the changes to attributes, child elements, and text content. It is particularly useful for detecting dynamic modifications to the DOM made by the ad-blockers

Key features of Mutation Obserever API:

  • Asynchronous Observation: It operates in an asynchronous manner, which means it won't block the main thread while monitoring DOM changes.
  • Wide Scope: It can be used to observe changes to child elements, attributes, and text content within the DOM.
  • Callback Function: The API triggers a callback function whenever a change is detected, enabling developers to respond in real-time.

How Ad-Blockers Affect DOM Elements?

Ad-blockers typically work by either blocking or removing elements in the DOM that are associated with ads. This can include elements that are hiding with specific class names or entirely removing ad-related <script> tags.

Detecting DOM Modifications by Ad-Blockers

Using the Mutation Observer API, you can monitor these modifications and detect when an ad-blocker is at work. This allows you to take appropriate action, such as notifying the user or loading alternative content.

Ad-blockers usually work by blocking or removing elements associated with ads. Such examples includes

  • <iframe>
  • <div>
  • <script>

. By using the Mutation Observer API, you can monitor for the removal or alteration of these elements and take appropriate action if they are found to be used.Now lets see the implementation of the mutation observer api to dedect the ad blockers with a simple example.

Steps To Detect Ad-Blocker

Follow the below folder struture for your project:

FolderSTRUCTURE
Fig: Folder structure

Since the project involves in tracking the ad block in the frontend of the website, for simplicity purposes, we are not using any backend functionalities and hence no dependencies required.

Step 1:

Create an Element to Observe the changes made by the ad-blocker. Firstly, create a dummy ad element that you expect to be removed or hidden by an ad-blocker.

HTML
<!DOCTYPE html> <html>  <head>     <title>Page Title</title> </head>  <body>     <div id="ad-container">         <p>This is a sample ad</p>     </div> </body>  </html> 


Step 2:

Initialize the Mutation Observer for tracking the changes in the HTML tags.Set up the Mutation Observer to watch for changes in the ad element.

JavaScript
// Select the target node (ad element) const adContainer = document.getElementById('ad-container');  // Callback function to execute when mutations are observed const callback = function (mutationsList, observer) {     for (let mutation of mutationsList) {         if (mutation.type === 'childList' && mutation.removedNodes.length > 0) {             console.log('Ad-blocker detected: Ad element was removed.');             // Take action, e.g., show a message or alternative content         }     } };  // Create an observer instance linked to the callback function const observer = new MutationObserver(callback);  // Start observing the target node for configured mutations observer.observe(adContainer, { childList: true }); 

Step 3:

Handle the Ad-Blocker Detection.When the ad element is removed successfully, the Mutation Observer's callback function will be trigger. You can then display an appropriate message to the user or load alternative content.

JavaScript
const showMessage = () => {     const message = document.createElement('div');     message.innerText = 'We noticed you are using an ad-blocker.      Please consider disabling it for our site.';     document.body.appendChild(message); };  const adContainer = document.getElementById('ad-container');  const callback = function(mutationsList, observer) {     for (let mutation of mutationsList) {         if (mutation.type === 'childList' && mutation.removedNodes.length > 0) {             console.log('Ad-blocker detected: Ad element was removed.');             showMessage();         }     } };  const observer = new MutationObserver(callback); observer.observe(adContainer, { childList: true }); 

Step 4:

Handle the Attribute Changes.You can also monitor for changes to attributes of the ad element. This can detect cases where an ad-blocker hides the element instead of removing it.This is a rare case and if you are really dependent on the ads for your websites to run and you are afraid of keen users, you can make use of this step.

observer.observe(adContainer, { attributes: true, childList: true });

Output:


Next Article
How To Detect ad-blocker Using Mutation Observer API ?

T

tmpravi5i5j
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Web-API

Similar Reads

    How to detect Adblocker using JavaScript ?
    In this article, we will be developing an adblocker detector using JavaScript. Adblocker is an extension that is used to block the ads which are served by the website. Adblocker blocks the DOM and the script which has the code to show ads. The adblockers have massive data of blocklist file names and
    3 min read
    How to detect the version of a browser ?
    This article includes the basic theory and technique of browser detection in JavaScript-enabled web browsers. Description: Even though most of the scripts work on JavaScript-enabled web browser, there are certain things that is not going to work on some browsers i.e. they are browser dependent and i
    4 min read
    Introduction to Intersection Observer
    Intersection Observer is an API that is used to detect the interaction of a target element with its's ancestor element or the document viewport. For example, if we want to detect if some element is visible in the viewport we can use this API for that purpose.Some of the use cases of Intersection Obs
    5 min read
    How to Block Ads on your Android Phone or Tablet?
    In today's digital age, Ads are everywhere, invading almost every part of our online activities. While ads serve as a primary revenue source for many websites and apps, they can often be intrusive, disruptive, and even malicious. On Android devices, these ads not only interrupt our browsing and app
    4 min read
    How to get userAgent information in Selenium Web driver?
    When utilizing Selenium WebDriver for the automation of web tests, it is frequently essential to retrieve the user agent string of a browser. The user agent conveys details regarding the browser and operating system, which can be instrumental in assessing how a web application performs in diverse en
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences