简介

在Vue中添加Google AdSense会遇到很多问题:

  • 广告位不显示
  • 广告位只显示第一个
  • 广告位都显示了,但是console中google AdSense代码报错
  • Vue报错,提示templates中不能使用<script>标签

作者把所有的坑都走了一遍之后,整理成本文,方便读者。

核心原理

当我们在Google AdSense中获取到广告位代码后,常见的广告位代码主要分为三部分:

  • Google AdSense js引入文件,通过script标签引入https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2626122653479680类似这样的JS。
  • Google AdSense Ins广告标签
  • Google AdSense 启动JS脚本代码(adsbygoogle = window.adsbygoogle || []).push({});

当我们需要在Vue中引入以上代码时,会遇到第一个问题:

[Vue warn]: Error compiling template:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

主要原因就是,Vue Templates中是不允许再出现Script标签的。虽然我们可以通过type来规避这个报错:type="application/javascript",但这并不能彻底解决问题。

当你把script标签写在Vue templates中时,因为Vue会根据数据的变化动态渲染页面,会导致多次运行该代码。具体到Google AdSense的广告位代码,就会报错:

message: "adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them."

上面的报错主要是因为多次执行adsbygoogle.push(),换句话说就是push()函数的运行次数和<ins>广告位的数量不匹配,根本原因就是Vue多次渲染模板,导致push()函数多次运行造成的。

解决办法

  • Google AdSense js文件引入代码,可以放到HTML网页的header中,引入一次即可。不需要每个广告位都引入一次。
  • (adsbygoogle = window.adsbygoogle || []).push({});启动脚本,不要直接放到Vue Templates中。可以自定义一个window全局函数,把改代码放入其中,然后在Vue的mounted生命周期中调用。代码如下:

定义js window全局函数:

window['addAds'] = function(){
    let childList = document.getElementsByClassName('gads');
    for (let i = 0; i < childList.length; i++) {
        (adsbygoogle = window.adsbygoogle || []).push({});
    }
}

重要提示:如果你的Google AdSense广告宽度、高度有问题,无法自适应广告位!请把上面的代码放到window.onload=function(){}中执行。具体可以参考文章:Google AdSense广告高度宽度错误、无法自适应的完美解决方案

Vue Templates中引入Google AdSense广告位:

<div class="gads">
    <!-- 右侧边栏 -->
    <ins class="adsbygoogle"
        style="display:block"
        data-ad-client="ca-pub-2626122653479680"
        data-ad-slot="8640757447"
        data-ad-format="auto"
        data-full-width-responsive="true"></ins>
</div>

Vue Mounted中调用window全局函数,启动Google AdSense广告:

mounted() {
    window.addAds();
}

大功告成!

效果展示

本站的Google AdSense广告就是通过以上代码展示的,效果如下图:

原文地址:vue页面中添加Google AdSense的正确方法-CoderBBB

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注