在 Angular 網站部署 Google 廣告

波波你行發表於2019-09-03

原文地址:http://www.bowen-tech.top/articles/detail/...

在Angular開發的網站部署Google廣告

Google廣告程式碼是包含script程式碼的,如果直接複製Google廣告到Angular的html頁面上,編譯時是會去除掉script標籤程式碼,具體可看這個GitHub文章:傳送門

新建component

  • component的template寫上google廣告的程式碼,不包含script標籤的程式碼,如下:
 template: `<div>
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-client="ca-pub-xxxxxxx"
         data-ad-slot="xxxxx"
         data-ad-format="auto"
         data-full-width-responsive="true"></ins>
  </div>`
  • init方法初始化window.adsbygoogle
ngAfterViewInit() {
    try{
      (window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
    }catch(e){
      console.error("error");
    }
  • 完整程式碼
import { Component, AfterViewInit} from '@angular/core';
// <!-- tools網站紀念日計算橫幅廣告 -->
@Component({
  selector: 'app-commemoration-ad',
  template: `<div>
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-client="ca-pub-xxxxxxx"
         data-ad-slot="xxxxx"
         data-ad-format="auto"
         data-full-width-responsive="true"></ins>
  </div>`
})
export class CommemorationAdComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    try{
      (window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
    }catch(e){
      console.error("error");
    }
  }

}

html引入模組

<!--在您希望展示廣告的html中新增此內容-->
<app-commemoration-ad></app-commemoration-ad>

index.html引入js檔案

<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

注意

如果是定義的公共模組,需要在模組裡面申明

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章