development

Gatsby 사이트에 애드센스(AdSense) 적용하기

여름싼타 2022. 11. 29. 13:22
반응형

Gatsby로 만든 사이트 애드센스(AdSense) 적용하는 방법

- 원글 : https://qiita.com/bob_yama/items/2b24fca112587a1bf8e8

 

Gatsby SSR 대응하는 방법이나 표시되는 화면의 크기에 따라 광고의 표시 숨기기를 전환하는 방법 등의 내용이다. 애드센스 자신의 사이트를 등록하는 방법등은 검색하면 여러가지 사이트에서 소개되고 있다고 생각하므로 이번은 생략한다.

 

Google 애드센스를 사이트에 적용하려면 적절한 스크립트 태그를 헤더에 추가해야 한다. 그것을 해주는 것이 gatsby-plugin-google-adsense | GatsbyJS 라는 플러그인이다. npm 또는 yarn으로 설치하고 gatsby-config.js 다음 설정을 추가한다.

plugins: [
    {
        resolve: `gatsby-plugin-google-adsense`,
        options: {
            publisherId: `ca-pub-xxxxxxxxxx`
        },
    },
]

 

 

애드센스 구성요소

그리고는 광고를 표시하고 싶은 부분에 적당한 dom 요소를 추가한다. 애드센스에서는 적절한 속성이 설정된 ins 요소를 배치하여 광고가 게재되는 위치를 지정할 있다. 그러나 단순히 ins 요소를 배치하면 광고가 게재되지 않는다. ins 요소가 dom 트리에 추가되었음을 애드센스 스크립트에 알리려면 다음 javascirpt 코드를 실행해야.

window.adsbygoogle = window.adsbygoogle || []
window.adsbygoogle.push({})

 

window 객체에 새로 추가된 adsbygoogle 속성과 ins 태그 간의 관계는 아래 사이트를 참고하면된다.

React로 Google 애드센스 로딩 문제 해결 - M@0_T55 - Medium

요컨대 추가된 ins 요소와 같은 수만큼 adsbygoogle 객체를 push해야 하는 같다. 이러한 규칙을 가미하면 React 구성 요소는 다음과 같다.

const AdSense = ({ format = "auto" }) => {
  useEffect(() => {
    if (window) {
      window.adsbygoogle = window.adsbygoogle || []
      window.adsbygoogle.push({})
    }
  })

  return (
    <div>
      <Ins
        className="adsbygoogle"
        data-ad-client="ca-pub-xxxxxxxxxxxxxxx"
        data-ad-slot="xxxxxxxx"
        data-ad-format={format}
      />
    </div>
  )
}

const Ins = styled.ins`
  display: block
`

 

Gatsby에서는 SSR에 의해 javascript 코드가 서버측에서 html을 빌드할 때와 브라우저에 로드되었을 때의 2회 실행된다.
클라이언트가 사이트에 액세스했을 때는, 사전에 빌드한 html을 표시시켜 최초 로드 시간을 단축시키면서, React 요소 트리가 구축할 수 있으면 그것을 실 DOM 트리에 hydrate 하는 구조로 되어 있다고 한다.

서버 측에서 html을 렌더링 할 때는 window 나 document 등의 객체에 액세스 할 수 없으므로 if 문을 사용하여 브라우저 측에서만 코드가 실행되도록한다. 또한 userEffect hook을 사용하여 DOM 트리가 빌드 된 후에 코드가 실행되도록한다. (클래스 컴퍼넌트를 사용하고 있는 경우는 useEffect내의 내용을 componentDidMount에 옮기면 문제 없게 작동한다.)

 

 

반응형 대응

화면 크기에 따라 광고 표시 숨기기를 전환하고 싶었으므로 다음과 같은 ResponsiveAdSense 만들었다.
번째 마운트시 Windows에서 화면 너비를 가져 와서 setStaet 호출하여 구성 요소를 재구성하고 광고를 게재한다.

AdSense.Responsive = ({ format = "auto" }) => {
  const [state, setState] = useState({ showAds: false })

  useEffect(() => {
    if (state.showAds) {
      window.adsbygoogle = window.adsbygoogle || []
      window.adsbygoogle.push({})
    }
    if (window) {
      const minWidth = responsive.tablet.minWidth // 769
      const shouldShowAds = window.innerWidth >= minWidth
      if (shouldShowAds) {
        setState({ showAds: true })
      }
    }
  }, [state.showAds])

  if (!state.showAds) return null

  return (
    <div>
      <Ins
        className="adsbygoogle"
        data-ad-client="ca-pub-xxxxxxxxxxxxxxxxxxx"
        data-ad-slot="xxxxxxxxxx"
        data-ad-format={format}
      />
    </div>
  )
}

const Ins = styled.ins({
  display: "block"
})
반응형