Not able to connect AdSense to Gatsby blog

551 views Asked by At

I've been trying to connect my AdSense account with my Gatsby blog and it seems impossible. AdSense is asking me to place this code between the head tag of my html

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

I've tried gatsby adsense plugins and other things and AdSense keeps telling me the code is not in the website. Since the website is hosted in S3, I downloaded the generated index.html and changed the code and re uploaded it. I think the problem is due to an added attribute called data-checked-head to the script tag, so even though I add the code above, what I see in the browser is this:

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

If this code is what AdSense sees, then of course he doesn't recognize it. Does anyone know what can I do in this case?? Or why is this attribute even there?? Thanks

3

There are 3 answers

0
EliteRaceElephant On

I can't answer about the details of AdSense but I have had problems with meta tags in the head of HTML myself. Here's two possibilites to debug your code in regards to Gatsby:

  1. Many plugins are disabled by default in development mode. Try gatsby build and gatsby serve and then check if it works with plugins.

  2. Use react-helmet to place your script tag in the head of HTML. Use gatsby build and gatsby serve for testing this as well.

0
AudioBubble On

You can use gatsby-plugin-google-adsense for displaying ads on your site.

0
Domenico Ruggiano On

The best way I found is from this article, which suggest a simple React implementation of Google AdSense.

In your gatsby-ssr.js file:

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)
}

Then you create a Banner component to include in your Gatsby.js pages:

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="banner-container">
      <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>
  )
}

Full article here.