シェル(@takasqr)のブログ

NuxtでGoogle Adsense広告を表示する【ライブラリなし】

NuxtでGoogeleアドセンス広告を表示したい

アドセンスの広告を表示しようとする時にサイトに下のようなコードを貼り付けるように表示されると思います。

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxx"
     crossorigin="anonymous"></script>
<!-- ヘッダー -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
     data-ad-slot="xxxxxxxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

ですがこのコードをNuxtの.vueに貼り付けてもうまくいきません。

そこで、Nuxt.jsで使えるようにコードをカスタマイズする方法を紹介します。 カスタマイズといってもかなり簡単です。

.vueコンポーネントの部分はVue.jsでも使えると思います。

この記事を書いた人

@takasqr アプリケーション開発が大好きなエンジニア。Vue、Swift、Electrom などでアプリを作って公開している。AWS や Firebase などのクラウドサービスも好き。

作ったアプリKeyScript

手順

  1. nuxt.config.jsでライブラリ読み込み
  2. 広告部分をAdInPost.vueにコンポーネント化
  3. 広告コンポーネントを別コンポーネント(post.vue)から呼び出し

1. nuxt.config.jsでライブラリ読み込み

export default {
  head: {
    script: [
      {
        src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxx',
        async: true,
        crossorigin: 'anonymous'
      }
    ]
  }
}

2. 広告部分をAdInPost.vueにコンポーネント化

<template>
  <ins
    class="adsbygoogle"
    style="display:block"
    data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
    data-ad-slot="xxxxxxxxxx"
    data-ad-format="auto"
    data-full-width-responsive="true"
  />
</template>

<script>
export default {
  mounted () {
    const adsbygoogle = window.adsbygoogle || []
    adsbygoogle.push({})
  }
}
</script>

3. 広告コンポーネントを別コンポーネント(post.vue)から呼び出し

<template>
  <AdInPost />
</template>

<script>
import AdInPost from '@/components/component/AdInPost.vue'

export default {
  components: {
    AdInPost
  }
}
</script>

これで広告部分をコンポーネント化することが出来たので他の場所でも使い回すことができるようになりました。