Search code examples
javascriptgoogle-chrome-extensiongoogle-ads-apiadsensegoogle-ad-manager

How to remove/replace Google Ads div with a custom div


I'm building a Chrome extension for educational purposes that removes/replaces a GoogleAds div with my custom div.

How do I locate the google-ad divs? Is there a specific id or class associated with it?

This is how I'm injecting my code into the website:--

content-script.js

var div=document.createElement("div"); // is there any specific divID associated with it?
document.body.appendChild(div); 
div.innerText="test123";

EDIT 1

Updating the structure as requested by @rabsom

<div class="q-box qu-pb--small" style="box-sizing: border-box;">
   <div class="q-box qu-cursor--pointer dom_annotate_google_ad" id="div-gpt-ad-1633993162946-0-init-a" style="box-sizing: border-box;" data-google-query-id="CNy0k-Dxiv8CFYCFZgId2jkKvA">
      <div id="google_ads_iframe_/21680945556/li_stick_home_and_ad_react_0__container__" style="border: 0pt none; margin: auto; text-align: center; width: 300px; height: 250px;">
        <iframe frameborder="0" src="https://515625e180dff516c1055c5fa3af1b19.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" id="google_ads_iframe_/21680945556/li_stick_home_and_ad_react_0" title="3rd party ad content" name="" scrolling="no" marginwidth="0" marginheight="0" width="300" height="250" data-is-safeframe="true" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" role="region" aria-label="Advertisement" tabindex="0" data-google-container-id="1" style="border: 0px; vertical-align: bottom;" data-load-complete="true"></iframe>
      </div>
   </div>
</div>

EDIT 2

I'm able to use the googletag now. However, it shows up after the ads have been loaded. So, I wait for the DOM to be loaded completely.

document.addEventListener('readystatechange', event => {
    if (event.target.readyState === "complete") {
        for (i = 0; i < googletag.pubads().getSlots().length; i++) {
            var slotDomId = googletag.pubads().getSlots()[i].getSlotElementId();
            document.getElementById(slotDomId).innerHTML = '<h1>yourcustomInnerHTML</h1>';
        }
    }
});

I try the above code, but even after the DOM has been loaded, it shows googletag as undefined.


Solution

  • For Google Ad Manager served ads, you do :

    for(i=0;i<googletag.pubads().getSlots().length;i++) {
     var slotDomId = googletag.pubads().getSlots()[i].getSlotElementId();
     document.getElementById(slotDomId).innerHTML = 'yourcustomInnerHTML';
    }
    

    Related documentation here.

    Note that this method is only available for sites using the Google Publisher Tag (Google Ad Manager library). For Adsense, you could use the following (assuming the Adsense slots are integrated within a parent div) :

    var adsenseBlocks = document.querySelectorAll('ins.adsbygoogle');
    for(i=0;i<adsenseBlocks.length;i++) {
     var slotDomId = adsenseBlocks[i].parentNode.id
     document.querySelector('#'+ slotDomId).innerHTML = 'yourcustomInnerHTML';
    }
    

    EDIT

    Regarding your need to run it from a Chrome extension, you have to inject the script into the tab DOM to get the objects rendered values.

    Here is a way to do so :

    manifest.json

    {
      "name": "Your Extension Name",
      "action": {},
      "manifest_version": 3,
      "version": "0.1",
      "description": "blablabla",
      "permissions": [
            "activeTab",
            "webNavigation",
            "scripting"
        ],
      "host_permissions": [
        "https://*/"
      ],
      "background": {
        "service_worker": "service-worker.js"
      },
      "web_accessible_resources": [{
            "resources": ["pageScript.js"],
            "matches": ["<all_urls>"]
      }]
    }
    

    service-worker.js

    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
      
    function insertScript() {
        var s = document.createElement('script');
        s.src = chrome.runtime.getURL('pageScript.js');
        s.onload = function() { this.remove(); };
        (document.head || document.documentElement).appendChild(s);
    }
    
      chrome.webNavigation.onCompleted.addListener((tab) => {
        chrome.scripting.executeScript(
          {
            target: { tabId: tabId },
            func : insertScript
          });
      });
    
    });
    

    pageScript.js

    function customHTML() {
       for (i = 0; i < googletag.pubads().getSlots().length; i++) {
            var slotDomId = googletag.pubads().getSlots()[i].getSlotElementId();
            document.getElementById(slotDomId).innerHTML = '<h1>yourcustomInnerHTML</h1>';
          }
        }
        
     //add GPT eventlisteners to detect refresh & lazyloaded ads
     googletag.pubads().addEventListener("slotOnload", (event) => {
          const slot = event.slot;
          customHTML();
        });