LoginSignup
7
6

More than 5 years have passed since last update.

Angular 5(SPA)でGoogle Adsenseを利用する方法

Last updated at Posted at 2018-05-19

google adsense(レスポンシブ広告)追加について

レスポンシブ広告を新規に作成すると以下のようなものが提供され、通常はそのまま貼るはず。ですが、Angularで作成するSPAの場合、componentとして追加(ng generate component してcomponent.htmlに記載)しても上手く表示されなかったため、別の手段を探しました。

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- angular_xem_harvest_checker -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-38663342XXXXXXX"
     data-ad-slot="65476XXXXX"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

ng2-adsense

こちらを利用します。
https://www.npmjs.com/package/ng2-adsense

インストール

> npm install ng2-adsense

設定

  • importsにモジュール、パラメータを追加。adClientとadSlotはレスポンシブ広告のコードを参照すればOK。
~\app01\src\app\app.module.ts
    AdsenseModule.forRoot({
      adClient: 'ca-pub-38663342XXXXXXX',
      adSlot: 65476XXXXX
    }),
  • index.htmlにadsense用のjs読み込み設定

headタグの中に<script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script>を追加。

~\app01\src\index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>sample app</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script>
</head>
  • 表示したい箇所のhtmlに、以下を追加。

例えばapp.component.htmlに以下を記載。

~\app01\src\app\app.component.html
<ng-adsense></ng-adsense>

以上で表示できるようになりました。

7
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6