oktay tontaş
oktay tontaş

Reputation: 271

How to use Google Publisher Tags Ads correctly in Nuxt Composition Api projects?

I use Compositon Api and ı implemented GPT ad service. It works well when I first time loaded page but if i switch between pages , my ad area disappears and and I get error messages.

ads.js

export const adIntegration = () => {
  const adScript = document.createElement('script');
  adScript.type = 'text/javascript';
  adScript.src = 'https://securepubads.g.doubleclick.net/tag/js/gpt.js';
  document.head.appendChild(adScript);
 
};
  
export const mainPageAd = ({ path, size, id }) => {
 
  adIntegration();

  window.googletag = window.googletag || { cmd: [] };

  googletag.cmd.push(() => {
    googletag.defineSlot(path, size, id).addService(googletag.pubads());
    googletag.pubads().enableSingleRequest();
    googletag.enableServices();
    googletag.display(id);
  }); 

};

index.vue

<template lang="pug">
.home-page 
    .advertisement( :id="adSlot.id" style='min-width: 955px; min-height: 240px')
     
<script>
import { mainPageAd } from '~/common/utils/ads';

setup(){ 

 const adSlots = ref({
      path: '/21737763597/adunit-1',
      size: [320, 100],
      id: 'div-gpt-ad-1559997122392-0',
    });

 onMounted(() => {
  mainPageAd({ path: adSlot.value.path, size: adSlot.value.size, id: adSlot.value.id });
    
}

return{adSlots}

My errors

first : Error in googletag.defineSlot: Cannot create slot /1347001/main-masthead. Div element "div-gpt-ad-1559997122392-0" is already associated with another slot: /1347001/main-masthead.

second : pubads_impl_2022092701.js?cb=31069995:18 Exception in queued GPT command TypeError: Cannot read properties of null (reading 'addService')

Upvotes: 1

Views: 1087

Answers (1)

oktay tontaş
oktay tontaş

Reputation: 271

export const adIntegration = () => {
  const adScript = document.createElement('script');

  adScript.type = 'text/javascript';
  adScript.src = 'https://securepubads.g.doubleclick.net/tag/js/gpt.js';
  document.head.appendChild(adScript);
};

export const mainPageAd = ({ path, size, id }) => {
  adIntegration();

  if (window.googletag) window.googletag.pubads().refresh();

  window.googletag = window.googletag || { cmd: [] };

  googletag.cmd.push(() => {
    googletag.defineSlot(path, size, id).addService(googletag.pubads());
    googletag.pubads().enableSingleRequest();
    googletag.enableServices();
    googletag.display(id);
  });
};

Upvotes: 1

Related Questions