Socket
Socket
Sign inDemoInstall

@capacitor-community/admob

Package Overview
Dependencies
Maintainers
31
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@capacitor-community/admob

A native plugin for AdMob


Version published
Weekly downloads
782
decreased by-20.61%
Maintainers
31
Weekly downloads
 
Created
Source

npm version

All Contributors

✅ Please check

This is development README for Capacitor v3. If you use v1 or v2, please check ./README_v2.md

@capacitor-community/admob

Capacitory community plugin for AdMob.

Maintainers

MaintainerGitHubSocialSponsoring Company
Masahiko Sakakibarardlabo@rdlaboRELATION DESIGN LABO, GENERAL INC. ASSOCIATION

Maintenance Status: Actively Maintained

Demo

Demo code is here.

Screenshots

BannerInterstitialReward
iOS
Android

Installation

% npm install --save @capacitor-community/admob@3.0.0-2
% npx cap update

Android configuration

In file android/app/src/main/java/**/**/MainActivity.java, add the plugin to the initialization list:

public class MainActivity extends BridgeActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerPlugin(com.getcapacitor.community.admob.AdMob.class);
    }
}

In file android/app/src/main/AndroidManifest.xml, add the following XML elements under <manifest><application> :

<meta-data
 android:name="com.google.android.gms.ads.APPLICATION_ID"
 android:value="@string/admob_app_id"/>

In file android/app/src/main/res/values/strings.xml add the following lines :

<string name="admob_app_id">[APP_ID]</string>

Don't forget to replace [APP_ID] by your AdMob application Id.

iOS configuration

Add the following in the ios/App/App/info.plist file inside of the outermost <dict>:

<key>GADIsAdManagerApp</key>
<true/>

<key>GADApplicationIdentifier</key>
<string>[APP_ID]</string>

<key>NSUserTrackingUsageDescription</key>
<string>[Why you use NSUserTracking. ex: This identifier will be used to deliver personalized ads to you.]</string>

Don't forget to replace [APP_ID] by your AdMob application Id.

Initialize

initialize(options: { requestTrackingAuthorization?: boolean , testingDevices?: string[]}): Promise<{ value: boolean }>

You can use option requestTrackingAuthorization. This change permission to require AppTrackingTransparency in iOS >= 14: https://developers.google.com/admob/ios/ios14

Default value is true. If you don't want to track, set requestTrackingAuthorization false.

Send and array of device Ids in `testingDevices? to use production like ads on your specified devices -> https://developers.google.com/admob/android/test-ads#enable_test_devices

Initialize for @ionic/angular

Open our Ionic app app.component.ts file and add this following code.

import { AdMob } from '@capacitor-community/admob';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  constructor() {
    // Initialize AdMob for your Application
    AdMob.initialize();
  }
}

Initialize for @ionic/react

This is implements simple sample from https://github.com/DavidFrahm . Thanks!

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { IonApp, IonRouterOutlet, isPlatform } from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router';
import Home from './pages/Home';

import { AdMob, AdOptions, AdSize, AdPosition } from '@capacitor-community/admob';

const App: React.FC = () => {
  AdMob.initialize();

  const adId = {
    ios: 'ios-value-here',
    android: 'android-value-here',
  };

  const platformAdId = isPlatform('android') ? adId.android : adId.ios;

  const options: AdOptions = {
    adId: platformAdId,
    adSize: AdSize.BANNER,
    position: AdPosition.BOTTOM_CENTER,
    margin: 0,
    // isTesting: true
    // npa: true
  };

  AdMob.showBanner(options);

  // Subscribe Banner Event Listener
  AdMob.addListener('onAdLoaded', (info: boolean) => {
    console.log('Banner ad loaded');
  });

  // Get Banner Size
  AdMob.addListener('onAdSize', (info: boolean) => {
    console.log(info);
  });

  return (
    <IonApp>
      <IonReactRouter>
        <IonRouterOutlet>
          <Route path="/home" component={Home} exact={true} />
          <Route exact path="/" render={() => <Redirect to="/home" />} />
        </IonRouterOutlet>
      </IonReactRouter>
    </IonApp>
  );
};

export default App;

APIs

BANNER

showBanner(options: AdOptions): Promise<{ value: boolean }>
import { AdMob, AdOptions, AdSize, AdPosition } from '@capacitor-community/admob';

@Component({
  selector: 'admob',
  templateUrl: 'admob.component.html',
  styleUrls: ['admob.component.scss'],
})
export class AdMobComponent {
  private options: AdOptions = {
    adId: 'YOUR ADID',
    adSize: AdSize.BANNER,
    position: AdPosition.BOTTOM_CENTER,
    margin: 0,
    // isTesting: true
    // npa: true
  };

  constructor() {
    // Show Banner Ad
    AdMob.showBanner(this.options);

    // Subscribe Banner Event Listener
    AdMob.addListener('bannerViewDidReceiveAd', (info: boolean) => {
      console.log('Banner Ad Loaded');
    });

    // Get Banner Size
    AdMob.addListener('bannerViewChangeSize', (info: boolean) => {
      console.log(info);
    });
  }
}
hideBanner(): Promise<{ value: boolean }>
// Hide the banner, remove it from screen, but can show it later
AdMob.hideBanner();
resumeBanner(): Promise<{ value: boolean }>
// Resume the banner, show it after hide
AdMob.resumeBanner();
removeBanner(): Promise<{ value: boolean }>
// Destroy the banner, remove it from screen.
AdMob.removeBanner();

INTERSTITIAL

import { AdMob, AdOptions } from '@capacitor-community/admob';

@Component({
  selector: 'admob',
  templateUrl: 'admob.component.html',
  styleUrls: ['admob.component.scss'],
})
export class AppComponent {
  options: AdOptions = {
    adId: 'YOUR ADID',
  };

  constructor() {
    // Subscribe interstitial Event Listener
    AdMob.addListener('onInterstitialAdLoaded', (info: boolean) => {
      AdMob.showInterstitial();
    });

    // Prepare interstitial banner
    AdMob.prepareInterstitial(this.options);
  }
}

RewardVideo

import { AdMob, AdOptions } from '@capacitor-community/admob';

@Component({
  selector: 'admob',
  templateUrl: 'admob.component.html',
  styleUrls: ['admob.component.scss'],
})
export class AdMobComponent {
  options: AdOptions = {
    adId: 'YOUR ADID',
  };

  constructor() {
    AdMob.addListener('onRewardedVideoAdLoaded', () => {
      AdMob.showRewardVideoAd();
    });
    AdMob.prepareRewardVideoAd(this.options);
  }
}

Index

API

initialize(...)

initialize(options: AdMobInitializationOptions) => Promise<void>

Initialize AdMob with AdMobInitializationOptions

ParamTypeDescription
optionsAdMobInitializationOptionsAdMobInitializationOptions

Since: 1.1.2


showBanner(...)

showBanner(options: AdOptions) => Promise<void>

Show a banner Ad

ParamTypeDescription
optionsAdOptionsAdOptions

Since: 1.1.2


hideBanner()

hideBanner() => Promise<void>

Hide the banner, remove it from screen, but can show it later

Since: 1.1.2


resumeBanner()

resumeBanner() => Promise<void>

Resume the banner, show it after hide

Since: 1.1.2


removeBanner()

removeBanner() => Promise<void>

Destroy the banner, remove it from screen.

Since: 1.1.2


prepareInterstitial(...)

prepareInterstitial(options: AdOptions) => Promise<void>

Prepare interstitial banner

ParamTypeDescription
optionsAdOptionsAdOptions

Since: 1.1.2


showInterstitial()

showInterstitial() => Promise<void>

Show interstitial ad when it’s ready

Since: 1.1.2


prepareRewardVideoAd(...)

prepareRewardVideoAd(options: AdOptions) => Promise<void>

Prepare a reward video ad

ParamTypeDescription
optionsAdOptionsAdOptions

Since: 1.1.2


showRewardVideoAd()

showRewardVideoAd() => Promise<AdMobRewardItem>

Show a reward video ad

Returns: Promise<AdMobRewardItem>

Since: 1.1.2


addListener(...)

addListener(eventName: 'bannerViewChangeSize', listenerFunc: (info: AdMobBannerSize) => void) => PluginListenerHandle
ParamTypeDescription
eventName"bannerViewChangeSize"bannerViewChangeSize
listenerFunc(info: AdMobBannerSize) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'bannerViewDidReceiveAd', listenerFunc: () => void) => PluginListenerHandle

Notice: request loaded Banner ad

ParamTypeDescription
eventName"bannerViewDidReceiveAd"bannerViewDidReceiveAd
listenerFunc() => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'bannerView:didFailToReceiveAdWithError', listenerFunc: (info: AdMobError) => void) => PluginListenerHandle

Notice: request failed Banner ad

ParamTypeDescription
eventName"bannerView:didFailToReceiveAdWithError"bannerView:didFailToReceiveAdWithError
listenerFunc(info: AdMobError) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'bannerViewWillPresentScreen', listenerFunc: (info: any) => void) => PluginListenerHandle

Notice: full-screen banner view will be presented in response to the user clicking on an ad.

ParamTypeDescription
eventName"bannerViewWillPresentScreen"bannerViewWillPresentScreen
listenerFunc(info: any) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'bannerViewWillDismissScreen', listenerFunc: (info: any) => void) => PluginListenerHandle

Notice: The full-screen banner view will be dismissed.

ParamTypeDescription
eventName"bannerViewWillDismissScreen"bannerViewWillDismissScreen
listenerFunc(info: any) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'bannerViewWillDismissScreen', listenerFunc: (info: any) => void) => PluginListenerHandle

Notice: The full-screen banner view will been dismissed.

ParamTypeDescription
eventName"bannerViewWillDismissScreen"bannerViewWillDismissScreen
listenerFunc(info: any) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'bannerViewDidDismissScreen', listenerFunc: (info: any) => void) => PluginListenerHandle

Notice: The full-screen banner view has been dismissed.

ParamTypeDescription
eventName"bannerViewDidDismissScreen"bannerViewDidDismissScreen
listenerFunc(info: any) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'adDidPresentFullScreenContent', listenerFunc: (info: any) => void) => PluginListenerHandle

Notice: Interstitial ad opened

ParamTypeDescription
eventName"adDidPresentFullScreenContent"adDidPresentFullScreenContent
listenerFunc(info: any) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'adDidDismissFullScreenContent', listenerFunc: (info: any) => void) => PluginListenerHandle

Notice: Dismiss Content

ParamTypeDescription
eventName"adDidDismissFullScreenContent"adDidDismissFullScreenContent
listenerFunc(info: any) => void

Returns: PluginListenerHandle

Since: 3.0.0


addListener(...)

addListener(eventName: 'didFailToPresentFullScreenContentWithError', listenerFunc: (info: AdMobError) => void) => PluginListenerHandle

Notice: Interstitial ad is be failed to open

ParamTypeDescription
eventName"didFailToPresentFullScreenContentWithError"didFailToPresentFullScreenContentWithError
listenerFunc(info: AdMobError) => void

Returns: PluginListenerHandle

Since: 3.0.0


Interfaces

AdMobInitializationOptions
PropTypeDescriptionDefaultSince
requestTrackingAuthorizationbooleanUse or not requestTrackingAuthorization in iOS(>14)1.1.2
testingDevicesstring[]An Array of devices IDs that will be marked as tested devices if {@link AdMobInitializationOptions.initializeForTesting} is true (Real Ads will be served to Testing devices but they will not count as 'real').1.2.0
initializeForTestingbooleanIf set to true, the devices on {@link AdMobInitializationOptions.testingDevices} will be registered to receive test production ads.false1.2.0
AdOptions
PropTypeDescriptionDefaultSince
adIdstringThe ad unit ID that you want to request1.1.2
adSizeAdSizeBanner Ad Size, defaults to SMART_BANNER. IT can be: SMART_BANNER, BANNER, MEDIUM_RECTANGLE, FULL_BANNER, LEADERBOARD, SKYSCRAPER, or CUSTOMSMART_BANNER1.1.2
positionAdPositionSet Banner Ad position. TOP_CENTER or CENTER or BOTTOM_CENTERTOP_CENTER1.1.2
isTestingbooleanYou can use test mode of ad.false1.1.2
marginnumberMargin Banner. Default is 0px; If position is BOTTOM_CENTER, margin is be margin-bottom. If position is TOP_CENTER, margin is be margin-top.01.1.2
npabooleanThe default behavior of the Google Mobile Ads SDK is to serve personalized ads. Set this to true to request Non-Personalized Adsfalse1.2.0
AdMobRewardItem

For more information https://developers.google.com/admob/android/rewarded-video-adapters?hl=en

PropTypeDescription
typestringRewarded type user got
amountnumberRewarded amount user got
PluginListenerHandle
PropType
remove() => Promise<void>
AdMobBannerSize

When notice listener of OnAdLoaded, you can get banner size.

PropType
widthnumber
heightnumber
AdMobError

For more information https://developers.google.com/android/reference/com/google/android/gms/ads/AdError

PropTypeDescription
codenumberGets the error's code.
messagestringGets the message describing the error.
causestringGets the cause of this error or null if the cause is nonexistent or unknown.
domainstringGets the domain of the error. MobileAds.ERROR_DOMAIN for Google Mobile Ads SDK errors, or a domain defined by mediation networks for mediation errors.

Enums

AdSize
MembersValueDescription
BANNER'BANNER'Mobile Marketing Association (MMA) banner ad size (320x50 density-independent pixels).
FLUID'FLUID'A dynamically sized banner that matches its parent's width and expands/contracts its height to match the ad's content after loading completes.
FULL_BANNER'FULL_BANNER'Interactive Advertising Bureau (IAB) full banner ad size (468x60 density-independent pixels).
LARGE_BANNER'LARGE_BANNER'Large banner ad size (320x100 density-independent pixels).
LEADERBOARD'LEADERBOARD'Interactive Advertising Bureau (IAB) leaderboard ad size (728x90 density-independent pixels).
MEDIUM_RECTANGLE'MEDIUM_RECTANGLE'Interactive Advertising Bureau (IAB) medium rectangle ad size (300x250 density-independent pixels).
SMART_BANNER'SMART_BANNER'deprecated: A dynamically sized banner that is full-width and auto-height.
ADAPTIVE_BANNER'ADAPTIVE_BANNER'A dynamically sized banner that is full-width and auto-height.
CUSTOM'CUSTOM'To define a custom banner size, set your desired AdSize
AdPosition
MembersValueDescription
TOP_CENTER'TOP_CENTER'Banner position be top-center
CENTER'CENTER'Banner position be center
BOTTOM_CENTER'BOTTOM_CENTER'Banner position be bottom-center(default)

TROUBLE SHOOTING

If you have error:

[error] Error running update: Analyzing dependencies [!] CocoaPods could not find compatible versions for pod "Google-Mobile-Ads-SDK":

You should run pod repo update ;

License

Capacitor AdMob is MIT licensed.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Jean-Baptiste Malatrasi

💻

gant02

💻

Saninn Salas Diaz

💻

Nico Lueg

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Keywords

FAQs

Package last updated on 10 Apr 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc