Advertisement
A_GUES

Javascript block ads

May 30th, 2023
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 1. Identify the elements that represent ads on a webpage
  2. // In this example, we'll target elements with CSS classes that often indicate ads.
  3.  
  4. const adClassNames = [
  5.   'ad',
  6.   'ad-banner',
  7.   'ad-container',
  8.   // Add more class names as needed to cover different types of ads
  9. ];
  10.  
  11. // 2. Define a function to remove ads
  12.  
  13. function removeAds() {
  14.   // Iterate through all elements in the DOM and check if they have ad-related class names
  15.   const elements = document.getElementsByTagName('*');
  16.   for (let i = 0; i < elements.length; i++) {
  17.     const element = elements[i];
  18.     for (let j = 0; j < adClassNames.length; j++) {
  19.       if (element.classList.contains(adClassNames[j])) {
  20.         element.remove();
  21.         break; // Once an ad is removed, no need to check other class names for the same element
  22.       }
  23.     }
  24.   }
  25. }
  26.  
  27. // 3. Attach the removeAds function to relevant events, such as page load or DOM changes
  28.  
  29. window.addEventListener('load', removeAds);
  30. // You can also listen for other events like DOMContentLoaded, scroll, or AJAX requests
  31. // and call removeAds() accordingly to handle dynamically loaded ads.
  32.  
  33. // 4. (Optional) Create a button or trigger to manually remove ads
  34.  
  35. const adBlockButton = document.createElement('button');
  36. adBlockButton.textContent = 'Toggle Ad Blocker';
  37. adBlockButton.addEventListener('click', removeAds);
  38. document.body.appendChild(adBlockButton);
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement