为 Gatsby 静态站点添加 Adsense 广告

iNote-

对于使用 Gatsby 生成的静态站点,并不像 Wordpress 和 Ghost 等建站系统那样,成功插入广告代码并不简单。参考国外两篇博文,把方法总结如下:

  1. 在 Adsense 后台获得固定广告单元代码,不要使用自动代码,现在 Gatsby 还没办法实现自动加载 Adsense 广告。

    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <!-- post页广告 -->
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-client="ca-pub-2527854722096700"
         data-ad-slot="7748165687"
         data-ad-format="auto"
         data-full-width-responsive="true"></ins>
    <script>
         (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
    
  2. 国内小哥针对 react 网站开发了专门的 React-Adsense 插件。首先,cd 到 Gatsby 站点目录,安装插件。

    npm i react-adsense
    
  3. 复制 .cache目录下的 html.jssrc目录下。

    cp .cache / default-html.js src / html.js
    
  4. 将在 Adsense 后台获得的广告代码,如下两部分添加到 html.js 标签的 之间,需要对adsbygoogle进行定义。

    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <script dangerouslySetInnerHTML={{__html: '(window.adsbygoogle = window.adsbygoogle || []).push({});'}}></script>
    </body>
    </html>
    
  5. 在需要插入广告的页面如 post 等文件中,插入广告位。

    import React from 'react';
    import AdSense from 'react-adsense';
     
    // ads with no set-up
    <AdSense.Google
      client='ca-pub-7292810486004926'
      slot='7806394673'
    />
     
    // ads with custom format
    <AdSense.Google
      client='ca-pub-7292810486004926'
      slot='7806394673'
      style={{ width: 500, height: 300, float: 'left' }}
      format=''
    />
     
    // responsive and native ads
    <AdSense.Google
      client='ca-pub-7292810486004926'
      slot='7806394673'
      style={{ display: 'block' }}
      layout='in-article'
      format='fluid'
    />
     
    // auto full width responsive ads
    <AdSense.Google
      client='ca-pub-7292810486004926'
      slot='7806394673'
      style={{ display: 'block' }}
      format='auto'
      responsive='true'
      layoutKey='-gw-1+2a-9x+5c'
    />
    
  6. 等待广告生效。一般需要1-2天。

参考资料

[1]. Using Google AdSense with Gatsby

[2]. gatsbyにgoogleのadsenseを入れる方法

生活
发表于 2020-01-14,更新于 2024-04-16 阅读量: