javascriptangulartypescriptgoogle-dfp

How to use Google DFP in Angular?


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.


Solution

  • 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>