【问题标题】:Dynamic Adsense Insertion With JavaScript使用 JavaScript 进行动态 Adsense 插入
【发布时间】:2011-09-06 01:37:05
【问题描述】:

我不敢相信这是多么难以找到,但即使在 Google 开发人员文档中我也找不到。我需要能够动态地,only 使用 JavaScript 插入 adsense。我还查看了 StackOverflow,其他一些人也问过这个问题,但没有回应。希望这将是一个更好的解释,并会得到一些答复。

基本上,用户插入我的脚本,我们称它为my.js(目前不能说具体是什么。)my.js 已加载,在my.js 中,一些嵌入式媒体会显示在他们的页面上我需要以某种方式从以下位置附加生成的 HTML:

<script type="text/javascript"><!--
google_ad_client = "ca-pub-xxx";
/* my.js example Ad */
google_ad_slot = "yyy";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

在特定的&lt;div&gt;(或其他)元素内。有什么想法吗?

附注没有像 jQuery 这样的库,我无法将 HTML 插入页面,除非它通过 JavaScript 并且必须插入到我命名的特定 &lt;div&gt; 中(如果有帮助,我将 Sizzle 用于我的 JS 库)

【问题讨论】:

    标签: javascript api adsense sizzle


    【解决方案1】:

    其他答案提出的用于异步加载 AdSense 脚本的简单技术将不起作用,因为 Google 在 AdSense 脚本中使用了document.write()document.write() 仅在页面创建期间有效,当异步加载的脚本执行时,页面创建已经完成。

    要完成这项工作,您需要覆盖 document.write(),这样当 AdSense 脚本调用它时,您就可以自己操作 DOM。这是一个例子:

    <script>
    window.google_ad_client = "123456789";
    window.google_ad_slot = "123456789";
    window.google_ad_width = 200;
    window.google_ad_height = 200;
    
    // container is where you want the ad to be inserted
    var container = document.getElementById('ad_container');
    var w = document.write;
    document.write = function (content) {
        container.innerHTML = content;
        document.write = w;
    };
    
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://pagead2.googlesyndication.com/pagead/show_ads.js';
    document.body.appendChild(script);
    </script>
    

    该示例首先将本机document.write() 函数缓存在一个局部变量中。然后它会覆盖document.write(),并在其中使用innerHTML 注入Google 将发送到document.write() 的HTML 内容。完成后,它会恢复原生的 document.write() 函数。

    这个技术是从这里借来的:http://blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html

    【讨论】:

    • 没有测试过,但听起来很合理。很好的解决方法。另一方面,这种技术可以通过 google-ads 代码中的适当编程来抢占...
    • @enRaiser 我和你一样讨厌做这些事情,而且你当然不必使用它。 :-) 但是当我陷入困境时它救了我。它让我能够继续解决实际的业务问题,而不是与我无法控制的 AdSense 脚本作斗争。
    • 谢谢!唯一对我有用的东西。
    • @Irina Google 2021 年还在使用document.write()
    • @JohnnyOshika 哦妈妈咪呀,答案来自 2013 年!
    【解决方案2】:

    我的页面上已经有 adsense,但还在我的博客文章中将新广告注入到占位符中。在我想要注入广告的地方,我添加了一个带有“adsense-inject”类的 div,然后在文档准备好并且我知道已经为其他广告加载了 adsense 脚本时运行此脚本:-

        $(document).ready(function()
        {
            $(".adsense-inject").each(function () {
                $(this).append('<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3978524526870979" data-ad-slot="6927511035" data-ad-format="auto"></ins>');
                (adsbygoogle = window.adsbygoogle || []).push({});
            }); 
        });
    

    【讨论】:

    • 太棒了 - 这个解决方案是最简单且侵入性最小的。为我工作。
    • 嗨,你能解释一下这是做什么的吗:(adsbygoogle = window.adsbygoogle || []).push({});
    • @VladimirKostov,这直接来自提供给 AdSense 使用的代码。我敢打赌,它的目的是让客户端页面将需要呈现的广告传达给 AdSense 脚本。以这种方式执行此操作可以让广告排队,同时在后台异步加载 adsense 渲染脚本。
    【解决方案3】:

    这是一个更新的实现,如果您不需要使用通用的外部 javascript 包含管理广告,这很有用,在我的情况下,我有很多静态 html 文件,它运行良好。它还为我的 AdSense 脚本提供单点管理。

    var externalScript   = document.createElement("script");
    externalScript.type  = "text/javascript";
    externalScript.setAttribute('async','async');
    externalScript.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
    document.getElementsByTagName('body')[0].appendChild(externalScript);
    
    var ins   = document.createElement("ins");
    ins.setAttribute('class','adsbygoogle');
    ins.setAttribute('style','display:block;');/*add other styles if required*/
    ins.setAttribute('data-ad-client','ca-pub-YOUR-CLIENTID');
    ins.setAttribute('data-ad-slot','YOUR-SLOTID');
    ins.setAttribute('data-ad-format','auto');
    document.getElementsByTagName('body')[0].appendChild(ins);
    
    var inlineScript   = document.createElement("script");
    inlineScript.type  = "text/javascript";
    inlineScript.text  = '(adsbygoogle = window.adsbygoogle || []).push({});'  
    document.getElementsByTagName('body')[0].appendChild(inlineScript); 
    

    使用示例:

    <script type="text/javascript" src="/adinclude.js"></script>
    

    【讨论】:

    • 这是对 Google 官方标签的优雅重写。与 Vue.js 完美配合。
    【解决方案4】:

    如何让变量(google_ad_client 等)始终位于头部并像这样动态附加另一部分:

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
    myDIV.appendChild(script); 
    

    【讨论】:

      【解决方案5】:

      根据this page,可以动态生成脚本标签并填充它们的 src 字段 - 这是@noiv 建议的(我这里的版本应该是自包含的;不需要外部 html 或 js 库)。你试过这个吗?好像没那么难……

      function justAddAdds(target_id, client, slot, width, height) {
        // ugly global vars :-P
        google_ad_client = client;
        google_ad_slot = slot;
        google_ad_width = width;
        google_ad_height = height;
        // inject script, bypassing same-source
        var target = document.getElementById(target_id);
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
        target.appendChild(script);
      }
      

      【讨论】:

      • 这是很久以前的了,但是动态插入有问题。我确定在另一个 SO 线程上是有原因的,但是,是的,无论如何,它在一年前的 adsense 脚本中不起作用。你最近试过吗?
      • 不使用adsense,但我刚刚验证了这允许您在Jsfiddle 中执行任意外部JS...
      • 是的 :) 我知道它适用于随机文件,但有一个特定原因它不适用于 adsense,我现在不记得了,因为它已经有一段时间了
      • 不过,它仍然是一个有趣的工具。有点像穷人的 XmlHttpRequest...
      • 此技术不适用于 AdSense,因为 AdSense 在脚本内部使用 document.write。 document.write 仅在页面创建期间有效,并且由于您是异步加载脚本,因此在 AdSense 脚本执行时页面创建过程已经完成。在 Google 停止使用 document.write 之前,此技术将无法使用。有关 document.write 的更多信息:stackoverflow.com/a/802943/188740
      【解决方案6】:

      好的,这似乎对我有用,但与往常一样,如果 Google 更改他们的模型,这可能会被弃用并且不再有效。它只需要将 Google 提供的标准代码剥离为 3 个组成部分,它们是......

      1. Google JS 脚本链接(在整个页面中包含一次):&lt;script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;/script&gt;

      2. <ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="GOOGLE_KEY" data-ad-client="GOOGLE_CLIENT" data-ad-slot="GOOGLE_AD_ID"></ins> 标记包含 Google 提供的原始定义。这就是您将通过 JS 构建代码将其放入 DOM 中的任何地方。我倾向于使用.innerHTML 简单地将其作为字符串插入,但您可以使用document.createElement 并根据您的要求手动添加所有属性。我个人认为这两种方法都没有明显的优势,所以归结为 恕我直言。

      3. 构建页面后(通过您的 javascript 代码),最后调用构建 Google 广告:(adsbygoogle = window.adsbygoogle || []).push({});

      这种方法对我非常有用Google JS 调用(上面的 3 个)。并且它允许我重建一个列表并根据需要多次调用 Google Ad 构建(上面的 3 个)(例如下一页或更改每页的数量)。

      希望这会有所帮助。

      【讨论】:

        【解决方案7】:

        这有点好笑。我也很困惑。 Adsense 告诉我们:

        复制广告单元代码并将其粘贴到您网页的正文标记之间

        将此代码放置在您希望展示广告的位置。对每个页面上的每个单独的广告单元执行此操作。

        这意味着我们应该这样实现:

        $.ajax('/api/xxx',
          function(data) {
            var container = $("#container")
            for (var item of data) {
              container.append( handleItem(item) );
            }
            // and append ALL the code, include two script tags and one ins tag.
            container.append(
        `<div>
        <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <ins class="adsbygoogle"
            style="display:block"
            data-ad-client="ca-pub-xxx"
            data-ad-slot="xxx"
            data-ad-format="auto"
            data-full-width-responsive="true"></ins>
        <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
        </div>`)
          }
        )
        

        ???,只需将整个示例代码粘贴到您要展示广告的所有位置。

        【讨论】:

          【解决方案8】:

          您可以使用 setTimeout("adsenseladen()", 1);如果给予同意。

           <script type="text/javascript">
           function adsenseladen() {
           var script = document.createElement('script');
           script.type = 'text/javascript';
           script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
           document.body.appendChild(script);
           }
           </script>
          
          
           <ins class="adsbygoogle"
           style="display:block"
           data-ad-client="ca-pub-##########"
           data-ad-slot="##########"
           data-ad-format="auto"
           data-full-width-responsive="true"></ins>
          
           <script>
           (adsbygoogle = window.adsbygoogle || []).push({});
           </script>
          

          【讨论】:

            【解决方案9】:

            这些方法可以使用,但不适用于 https。如果您想动态放置广告并使用 https,则需要注册 Double Click For Publishers。

            我在我的网站上遇到了这个问题,所以我整理了一个 npm 模块来为自己解决这个问题。希望对您有用。

            Use Adsense in Single Page Web Apps

            该链接包含有关如何在单页 Web 应用程序中使用该模块的完整示例代码。

            安装模块后,此代码将在您指定的元素中展示您的广告: ViceView.showAdsense({adslot: {slot: "myslot", sizes: "[300,100]", id:"your adsenseid"}, element: "element", adwidth: 300, adheight: 100});

            【讨论】:

              猜你喜欢
              • 2016-10-05
              • 1970-01-01
              • 2014-03-12
              • 1970-01-01
              • 2011-10-22
              • 1970-01-01
              • 1970-01-01
              • 2013-07-10
              • 2011-02-01
              相关资源
              最近更新 更多