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

17

我想知道在哪里添加Google Adsense提供的<script></script>。他们说要将其添加到<head></head>中,但在Gatsby中,您可以使用Helmet作为<head>。 我还尝试在html.js文件中添加脚本,其中包含一个带有{``}<head>标记来转义<script>标记,但它会在网站顶部输出脚本内容。

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

  • 我尝试使用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>

来源:html.js

网站应该被Google爬虫检测到。


引号在浏览器中被转换为“"”。不确定是否有解决方法。 - Dr. Kevin Wang
请使用 dangerouslySetInnerHTML 来抑制浏览器错误。 - Dr. Kevin Wang
1
<script dangerouslySetInnerHTML={{ __html: '(adsbygoogle = window.adsbygoogle || []).push({google_ad_client: "something",enable_page_level_ads: true});', }} /> - Vic
5个回答

17
如果您使用类似于Netlify的服务来部署您的网站,您可以使用代码片段注入功能,使其在不触及源代码的情况下工作。然后,您可以选择要添加片段(脚本标记)的位置。对于Adsense,应该在“”之前添加。希望能有所帮助 :)

enter image description here


4
好的!我不必担心在 Github 上忽略任何东西。 - jhnferraris

16

感谢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>

最终,如果您想验证是否已添加Adsense,则可以控制与广告相关的<script>是否出现->在<head>标记内,您应该找到类似于<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>的内容。 - Joe Doe

3

您可以在这里找到一个关于如何在Gatsby中添加Google AdSense的好教程(链接)

基本上,建议的方法是使用React实现Google AdSense横幅,并将Google AdSense代码包含在gatsby-ssr.js文件中。

gatsby-ssr.js文件:

const React = require('react')

const HeadComponents = [
  <script
    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXX"
    crossOrigin="anonymous"
    async
  />,
]

exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents(HeadComponents)
}

AdSense横幅组件:

const Banner: React.FC<BannerProps> = ({
  className,
  style,
  layout,
  format,
  client = 'ca-pub-XXXX',
  slot,
  responsive,
  layoutKey,
}) => {
  useEffect(() => {
    try {
      const adsbygoogle = window.adsbygoogle || []
      adsbygoogle.push({})
    } catch (e) {
      console.error(e)
    }
  }, [])
  return (
    <div className={clx(container, className)}>
      <ins
        className="adsbygoogle"
        style={style}
        data-ad-layout={layout}
        data-ad-format={format}
        data-ad-client={client}
        data-ad-slot={slot}
        data-ad-layout-key={layoutKey}
        data-full-width-responsive={responsive}
      />
    </div>
  )
}

不要使用已被弃用的gatsby-adsense插件。
完整文章在这里

1
只是一点小提示,对于使用ES6的Gatsby V2,您需要使用export const onRenderBody而不是exports.onRenderBody - Ander

2
为了设置Adsense,在你的html.js中,在闭合的</body>标签之前插入<script>标签(不要使用模板文字{``}),如下所示:

Original Answer翻译成"最初的回答"
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
</body>

然后,要放置广告单元,您可以使用像react-adsense这样的预构建组件(如您所提到的),或者自己构建。 这是一篇有用的文章,涵盖了使用组件设置和放置广告单元的方法。
如果您有任何问题,请告诉我是否有效或是否有不清楚之处!

0

在 Gatsby 中添加 Google Adsense 需要这三个包:

react-adsense rehype-react gatsby-transformer-remark

如果你想知道如何在你的网站中实现这些包,那么请查看this tutorial


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接