iT邦幫忙

0

如何將 Google AdSense 添加到 Nuxt.js ?

  • 分享至 

  • xImage
  •  

第一步,將 Google AdSense 腳本添加到 head 標籤(app.html 文件內):

<script
  async 
  src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxx"
  crossorigin="anonymous">
</script>

第二:創建 Google Adsense 組件以在您想要的任何地方重複使用:

<div :class="classNames">
    <ins
      :className="adsbygoogle"
      :style="{display: 'block'}"
      :data-ad-client="googleAdId"
      :data-ad-slot="slot"
      data-ad-format="auto"
      data-full-width-responsive="true"
    ></ins>
  </div>

並使用下列script:

export default {
  name: "GoogleAd",
  props: {
    timeout: Number,
    classNames: String,
    slot: String
  },
  data() {
    return {
      googleInit: null,
      googleAdId: "ca-pub-yourGoogleAdId"
    };
  },
  mounted() {
  	let timeout = 200;
    if(this.timeout) timeout = this.timeout;
    this.googleInit = setTimeout(() => {
      if (typeof window !== "undefined")
        (window.adsbygoogle = window.adsbygoogle || []).push({});
    }, timeout);
  },
  destroyed() {
    if (this.googleInit) clearTimeout(this.googleInit);
  }
};

Props:

  • classNames: String => 添加自訂義的class風格給 Google Ads
  • slot: String => 插入 Google AdSense 給的slot值
  • timeout: Number (默認200ms) => 頁面呈現後,廣告的延遲時間(可有可無)

Note: 將ca-pub-yourGoogleAdId替換為自己的 Google Ad Id

最後,將您的 GoogleAd 組件添加到想要顯示的頁面中,ex:

<template>
  <GoogleAdSense slot="123456789" :timeout="200" classNames="mx-auto"/>
</template>

Script:

import GoogleAdSense from "~/components/GoogleAdSense";

export default {
  name: "App",
  components: {
    GoogleAdSense
  }
};

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言