简体   繁体   中英

How to implement Google Ad Manager (aka DFP) in a gatsby site?

In order to serve GAM/DFP ads on a gastby.js site, I am supposed to put this code in the head:

<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
      window.googletag = window.googletag || {cmd: []};
      googletag.cmd.push(function() {
        googletag.defineSlot('/22274312948/lm1_lb1', [728, 90], 'div-gpt-ad-1614985862735-0').addService(googletag.pubads());
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
      });
</script>

And this code in the body, where I want to show the ad:

<!-- /22274312948/lm1_lb1 -->
<div id='div-gpt-ad-1614985862735-0' style='width: 728px; height: 90px;'>
  <script>
    googletag.cmd.push(function() { googletag.display('div-gpt-ad-1614985862735-0'); });
  </script>
</div>

My gatsby site is based on MDX files, and I would like to place ads between the paragraphs, by calling them from the MDX file itself.

The <head> script can be placed in any React (so Gatsby) application using the <Helmet> component. Basically, all it is wrapped inside, it's placed in the <head> of your application. So, in any component, for example, the <Layout> you can:

import React from "react";
import {Helmet} from "react-helmet";

const Layout = ({ children }) => {
  return <section>
    <Helmet>
      <script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
      <script>
      {`window.googletag = window.googletag || {cmd: []};
      googletag.cmd.push(function() {
        googletag.defineSlot('/22274312948/lm1_lb1', [728, 90], 'div-gpt-ad-1614985862735-0').addService(googletag.pubads());
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
      });`}
      </script>
    </Helmet>
    <Header />
    <main>{children}</main>
  </section>;
};

Be careful when dealing with global objects such as window or document in Gatsby outside React's lifecycle, it may lead to hydration issues and caveats. Therefore, some of them are not available during the SSR ( S erver- S ide R endering) If you can use a Gatsby plugin rather than adding the script manually, I would strongly suggest doing it, for example, using the gatsby-plugin-google-adsense , simply using:

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `@isamrish/gatsby-plugin-google-adsense`,
      options: {
        googleAdClientId: "YOUR_GOOGLE_ADSENSE_TRACKING_ID",
        head: false // Optional
      }
    }
  ]
};

Regarding your MDX script, since your MDX files allow you to embed JSX logic (hence the name) you just can add it wherever you want:

import { Box, Heading, Text } from 'somewhere'

# Here is a JSX block

It is using imported components!

<Box>
  <Heading>Here's a JSX block</Heading>
  <Text>It's pretty neat</Text>
  <YourScriptComponent />
</Box>

In your YourScriptComponent.js you can just add your script like any other component, something like:

const YourScriptComponent = () =>{

return <>
    <!-- /22274312948/lm1_lb1 -->
    <div id='div-gpt-ad-1614985862735-0' style='width: 728px; height: 90px;'>
      <script>
        googletag.cmd.push(function() { googletag.display('div-gpt-ad-1614985862735-0'); });
      </script>
    </div>
</>
}

Updating the issue with the final fix for those who may help. The above workaround shows the path to add a GAM ad in a Gatsby/React site. The idea is to use the MDX to import a custom component that loads a promised-based component/module that contains the ad itself. Something like:

---

import DFPWrapper from '../../../src/components/DFPWrapper';

This is the body of the markdown

<DFPWrapper />

There, you can import an own or a third-party dependency, such as react-gpt :

const DFPWrapper = props => {
  return <>
    <Helmet>
      <script async src='https://securepubads.g.doubleclick.net/tag/js/gpt.js' />
      <script>
        {`window.googletag = window.googletag || { cmd: [] };
          googletag.cmd.push(function() {
          googletag.defineSlot('/22274312948/lm1_lb1', [728, 90], 'div-gpt-ad-1614985862735-0').addService(googletag.pubads());
          googletag.pubads().enableSingleRequest();
          googletag.enableServices();`}
      </script>
    </Helmet>
    <div>
      <GPT adUnitPath='/22274312948/lm1_lb1' slotSize={[728, 90]} />
    </div>
  </>
}

The information required for the react-gpt is stored in this line:

googletag.defineSlot('/22274312948/lm1_lb1', [728, 90], 'div-gpt-ad-1614985862735-0').addService(googletag.pubads());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM