如何删除/替换Google广告div为自定义div

huangapple go评论66阅读模式
英文:

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.
我正在构建一个用于教育目的的Chrome扩展程序,用于移除/替换GoogleAds的div。

How do I locate the google-ad divs? Is there a specific id or class associated with it?
如何定位google-ad divs?是否有特定的id或类与之关联?

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

更新如@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.

我现在可以使用googletag。然而,它在广告加载后才出现。因此,我等待DOM完全加载。

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.

我尝试上述代码,但即使在DOM加载完成后,它仍然显示googletag为未定义。

英文:

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(&quot;div&quot;); // is there any specific divID associated with it?
document.body.appendChild(div); 
div.innerText=&quot;test123&quot;;

EDIT 1

Updating the structure as requested by @rabsom

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

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(&#39;readystatechange&#39;, event =&gt; {
    if (event.target.readyState === &quot;complete&quot;) {
        for (i = 0; i &lt; googletag.pubads().getSlots().length; i++) {
            var slotDomId = googletag.pubads().getSlots()[i].getSlotElementId();
            document.getElementById(slotDomId).innerHTML = &#39;&lt;h1&gt;yourcustomInnerHTML&lt;/h1&gt;&#39;;
        }
    }
});

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

答案1

得分: 1

以下是您要翻译的内容:

对于由Google Ad Manager提供的广告,您可以:

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

相关文档在此

请注意,此方法仅适用于使用Google Publisher标签(Google Ad Manager库)的站点。对于Adsense,您可以使用以下方法(假设Adsense插槽已集成在父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';
}

编辑

关于您需要从Chrome扩展中运行它,您必须将脚本注入到标签DOM中以获取对象的渲染值。

以下是一种方法:

manifest.json

{
    "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>';
    }
}

// 添加GPT事件监听器以检测刷新和延迟加载的广告
googletag.pubads().addEventListener("slotOnload", (event) => {
    const slot = event.slot;
    customHTML();
});

请注意,这是您提供的内容的翻译。

<details>
<summary>英文:</summary>

For Google Ad Manager served ads, you do : 

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

Related documentation [here][1].

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(&#39;ins.adsbygoogle&#39;);
    for(i=0;i&lt;adsenseBlocks.length;i++) {
     var slotDomId = adsenseBlocks[i].parentNode.id
     document.querySelector(&#39;#&#39;+ slotDomId).innerHTML = &#39;yourcustomInnerHTML&#39;;
    }

**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*

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

*service-worker.js*

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

*pageScript.js*

 

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



  [1]: https://developers.google.com/publisher-tag/reference?hl=fr#googletag.Slot_getSlotElementId

</details>



# 答案2
**得分**: 0

有2个不同的标签我知道。

有一个名为**adsbygoogle**的类。你可以通过[这个][1]链接来查看它是如何静态添加到HTML文件中的。

除此之外,我还看到其他网站使用以**google_ads**开头的ID。要获取所有ID,你可以使用:

```javascript
document.querySelectorAll('div[id*="google"]').forEach(el=>{
    //你的代码在这里
})

请注意,这将返回容器div和iframe标签。

英文:

There are 2 different tags that i am aware of.

There is a class called adsbygoogle. You can access how it is added statically in to the html file with this link.

Other than that i have seen other websites use ids start with google_ads. In order to get all ids you can use;

document.querySelectorAll(&#39;div[id*=&quot;google&quot;]&#39;).forEach(el=&gt;{
        //your code here
})

Keep in mind that this will return the container div and the iframe tag as well.

huangapple
  • 本文由 发表于 2023年5月18日 02:44:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定