如何将Google Adsense添加到Gatsby网站?

时间:2020-10-05 12:07:58

标签: gatsby adsense

Google AdSense给我一个脚本,该脚本要添加到head标签中

<script data-ad-client="ca-pub-XXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

我的代码:

<Helmet>
  <script
   data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
   async
   src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
   ></script>
</Helmet>

返回此错误

AdSense头标记不支持data-react-helmet属性。 我该如何解决?

enter image description here

1 个答案:

答案 0 :(得分:1)

我通过将脚本添加到html.js中进行修复,我需要将head标签注入到每个页面内的全局上下文中,因此我将其放在html.js文件中,然后可以随时添加body标签。

另一种方法是像这样在gatsby-ssr.js中添加脚本:

const React = require("react")

const HeadComponents = [
 <script
   key="1-http-ads"
   data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
   async
   src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
   />,
]

exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents(HeadComponents)
}
相关问题