0

I want to use Google DFP (Google Publisher Tag) but it does not working.

I defined global variable which holds googletag:

googletag: any =  window.googletag || {};

Adding the script to the page:

addGPTScript() {

  // Ad gtp.js script in the page
  const gads = document.createElement('script');
  gads.async = true;
  gads.type = 'text/javascript';
  const useSSL = 'https:' === document.location.protocol;
  gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
  const node = document.getElementsByTagName('script')[0];
  node.parentNode.insertBefore(gads, node);

  if (this.googletag.apiReady) {
    console.log(this.googletag)
  }

  console.log(this.googletag)
}

ngOnInit(): void {
  this.addGPTScript();
}

But the first console.log in condition is never loaded and the second one prints undefined. I checked the HTML HEAD tag and found that script is added.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
  • `declare var googletag: any = window.googletag || {};` in `typings.d.ts` – Chrillewoodz Oct 16 '18 at 14:45
  • @Chrillewoodz My IDE says "TS1039: Initializers are not allowed in ambient contexts." – Maihan Nijat Oct 16 '18 at 14:51
  • https://stackoverflow.com/questions/42301181/initializers-are-not-allowed-in-ambient-contexts-error-when-installing-blueprint – Chrillewoodz Oct 16 '18 at 14:53
  • @Chrillewoodz thanks. Do I need to add the lib/script in the HEAD and adding it through JS code also? – Maihan Nijat Oct 16 '18 at 14:55
  • Should be able to have it in the body of the index.html, but then again I've never used that particular script so they might tell you otherwise. – Chrillewoodz Oct 16 '18 at 14:56
  • @Chrillewoodz I added in the head of document (without async attr) and added also through JS code and now the ` if (this.googletag.apiReady) { console.log(this.googletag) }` this works. But got `Exception in queued GPT command TypeError: "_this.googletag.googleTagletag is undefined"`. At least I have something to debug now. – Maihan Nijat Oct 16 '18 at 14:59

1 Answers1

1

I noticed the following code was not working:

  // Ad gtp.js script in the page
  const gads = document.createElement('script');
  gads.async = true;
  gads.type = 'text/javascript';
  const useSSL = 'https:' === document.location.protocol;
  gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
  const node = document.getElementsByTagName('script')[0];
  node.parentNode.insertBefore(gads, node);

I removed the above and added in the HTML Head tag:

<script type="text/javascript" async src="https://www.googletagservices.com/tag/js/gpt.js"></script>
Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110