如何将Adsense添加到使用GatsbyJS构建的网站上?

Joe*_*Doe 9 adsense head jsx reactjs gatsby

我想知道我应该在哪里添加<script></script>Google Adsense提供的内容。

他们说要将其添加到中<head></head>,但在盖茨比,您的头盔为<head>

我还尝试将脚本添加到html.js文件中,该文件位于该<head>标签的标签中,{``}以逃避该<script>标签,但是该脚本在网站顶部输出脚本内容。

TL; DR:将Adsense添加到使用GatsbyJS构建的网站的最佳方法是什么?

  • 我尝试使用react adsense软件包,但不了解如何在Gatsby中使用它。
  • 我试图将<script>标签添加到html.js中,但无法编译。
  • 如果您将其转义,则{``}可以在网站顶部按原样获取脚本。
<head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          {this.props.headComponents}
          {`<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>`}
             {` <script>
                  (adsbygoogle = window.adsbygoogle || []).push({
                    google_ad_client: "ca-pub-1540853335472527",
                    enable_page_level_ads: true
                  });
                </script> 
              `}
        </head>
Run Code Online (Sandbox Code Playgroud)

来源:html.js

该网站应被Google抓取工具检测到。

Lak*_*n S 15

如果您正在使用诸如Netlify部署您的网站之类的服务,您可以使用代码段注入功能来完成这项工作,而无需触及您的源代码。

settings -> build & deploy -> post processing -> snippet injection -> add snippet

然后您可以选择要添加代码段(脚本标签)的位置。对于Adsensethis 应该在</head>. 希望能帮助到你。:)

在此处输入图片说明

  • 好一个!我不必担心忽略 Github 上的东西 (3认同)

Joe*_*Doe 8

感谢在Github上给出的答案,终于解决了这个问题:

如果要添加Adsense:

  • cp .cache/default-html.js src/html.js
  • 添加脚本,但其中的所有内容均应转义-> { <some-js-code-here>}
  • 以我的情况为例:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
             <script>
                  {`
                    (adsbygoogle = window.adsbygoogle || []).push({
                      google_ad_client: "ca-pub-1540853335472527",
                      enable_page_level_ads: true
                    });
                  `}
             </script>
Run Code Online (Sandbox Code Playgroud)