【问题标题】:Can I make a Google ad display conditionally?我可以有条件地展示 Google 广告吗?
【发布时间】:2018-03-22 18:54:37
【问题描述】:

我的网站上有一种“免费增值”模式,这样如果用户订阅了,他们就看不到我在页面上的 Google Adsense 广告。

所以我想根据我的 Javasript 代码中的条件 if() 语句来制作 Adsense 广告是否显示。

但是,从 Google 获得的代码被设计为直接插入 HTML,而且不仅如此,他们还在做一些棘手的事情,包括在评论区域中设置一些变量,我无法理解周围。

这就是代码的样子:

<script type="text/javascript"><!--
google_ad_client = "xx-xxx-00000000000000000000";
/* karamoh */
google_ad_slot = "0000000000";
google_ad_width = 320;
google_ad_height = 50;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

是否有可能以这种方式转换它,以便我可以在它周围包裹一个if() 语句?

(我想我可以把它全部放在一个 document.write() 函数中,但这似乎太不优雅了。肯定有一种方法可以更直接地利用 Javascript 吗?)

【问题讨论】:

    标签: javascript adsense


    【解决方案1】:

    最干净的方法是检查服务器端是否您的客户端是高级的,并且根本不要在发送给客户端的页面中插入标签。

    如果您由于某种原因无法访问它并且不介意对 show_ads.js 的额外请求,似乎设置无意义的google_ad_client 会使 Adsense 服务回复 400 并且不绘制任何广告完全可以,因此您可以使用它来代替广告代码的第一行:

    if(premiumClient)
        google_ad_client = "some-nonsense-value"
    else
        google_ad_client = "your-correct-value"
    end
    

    另外测试表明,如果您输出带有document.write&lt;script&gt; 标记,它会阻止执行,就像它在文档中的真实情况一样,因此无论您自己建议什么,或者使用较少干扰的以下代码也可能会起作用:

    <script type="text/javascript"><!--
    google_ad_client = "xx-xxx-00000000000000000000";
    /* karamoh */
    google_ad_slot = "0000000000";
    google_ad_width = 320;
    google_ad_height = 50;
    //-->
    if(!premiumUser)
        document.write('<scr'+'ipt type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"><'+'/script>')
    </script>
    

    我不记得是否确实在任何地方保证它确实会阻止其余的执行,因此,由于 show_ads.js 中的另一个 document.write 它现在可能会在某些浏览器中失败,或者将来突然开始失败.

    【讨论】:

    • 我喜欢您的第二个建议,因为即使这意味着留下比我希望的多一点的代码,但如果我不拨打 Google 的 400 电话,高级用户的等待时间可能会更少回复。
    • 不幸的是,经过一些实验,这些方法似乎不起作用。我一直与 Google 支持人员取得联系,他们告诉我我需要在他们的 Adsense 代码中进行硬编码,否则将无法正常工作。您是否通过更改实施了上述任何一项建议并让它们发挥作用?我只是问,因为如果你有,那么也许我可以在 Google 支持下进一步提出这个问题。
    【解决方案2】:

    类似的东西怎么样:

    if(userIsNotSubscribed)
        document.getElementById("advertisementDiv").innerHTML = advertisement;
        // Where advertisement = The Code given to you by Google
    

    【讨论】:

    • 可能会失败,因为从广告标签调用的 show_ads.js 使用了 document.write,而且它往往不能很好地与真正动态的 DOM 访问配合使用。
    • JSONP 怎么样?这会引发问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多