Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@capacitor-community/admob

Package Overview
Dependencies
Maintainers
38
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

  • 4.0.0-0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
274
decreased by-57.59%
Maintainers
38
Weekly downloads
 
Created
Source


AdMob

@capacitor-community/admob

Capacitor community plugin for native AdMob.


Maintainers

MaintainerGitHubSocialSponsoring Company
Masahiko Sakakibarardlabo@rdlaboRELATION DESIGN LABO, GENERAL INC. ASSOCIATION
Saninn Salas DiazSaninn Salas Diaz@SaninnSalas

Maintenance Status: Actively Maintained

Contributors ✨

Made with contributors-img.

Demo

Demo code is here.

Screenshots

BannerInterstitialReward
iOS
Android

Installation

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

Android configuration

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

import android.os.Bundle;

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>SKAdNetworkItems</key>
<array>
  <dict>
    <key>SKAdNetworkIdentifier</key>
    <string>cstr6suwn9.skadnetwork</string>
  </dict>
</array>
<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.

Example

Initialize AdMob

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

export async function initialize(): Promise<void> {
  const { status } = await AdMob.trackingAuthorizationStatus();

  if (status === 'notDetermined') {
    /**
     * If you want to explain TrackingAuthorization before showing the iOS dialog,
     * you can show the modal here.
     * ex)
     * const modal = await this.modalCtrl.create({
     *   component: RequestTrackingPage,
     * });
     * await modal.present();
     * await modal.onDidDismiss();  // Wait for close modal
     **/
  }
 
  AdMob.initialize({
    requestTrackingAuthorization: true,
    testingDevices: ['2077ef9a63d2b398840261c8221a0c9b'],
    initializeForTesting: true,
  });
}

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

Show Banner

import { AdMob, BannerAdOptions, BannerAdSize, BannerAdPosition, BannerAdPluginEvents, AdMobBannerSize } from '@capacitor-community/admob';

export async function banner(): Promise<void> {
    AdMob.addListener(BannerAdPluginEvents.Loaded, () => {
      // Subscribe Banner Event Listener
    });

    AdMob.addListener(BannerAdPluginEvents.SizeChanged, (size: AdMobBannerSize) => {
      // Subscribe Change Banner Size
    });

    const options: BannerAdOptions = {
      adId: 'YOUR ADID',
      adSize: BannerAdSize.BANNER,
      position: BannerAdPosition.BOTTOM_CENTER,
      margin: 0,
      // isTesting: true
      // npa: true
    };
    AdMob.showBanner(options);
}

Show Interstitial

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

export async function interstitial(): Promise<void> {
  AdMob.addListener(InterstitialAdPluginEvents.Loaded, (info: AdLoadInfo) => {
    // Subscribe prepared interstitial
  });

  const options: AdOptions = {
    adId: 'YOUR ADID',
    // isTesting: true
    // npa: true
  };
  await AdMob.prepareInterstitial(options);
  await AdMob.showInterstitial();
}

Show RewardVideo

import { AdMob, RewardAdOptions, AdLoadInfo, RewardAdPluginEvents, AdMobRewardItem } from '@capacitor-community/admob';

export async function rewardVideo(): Promise<void> {
  AdMob.addListener(RewardAdPluginEvents.Loaded, (info: AdLoadInfo) => {
    // Subscribe prepared rewardVideo
  });

  AdMob.addListener(RewardAdPluginEvents.Rewarded, (rewardItem: AdMobRewardItem) => {
    // Subscribe user rewarded
    console.log(rewardItem);
  });

  const options: RewardAdOptions = {
    adId: 'YOUR ADID',
    // isTesting: true
    // npa: true
    // ssv: {
    //   userId: "A user ID to send to your SSV"
    //   customData: JSON.stringify({ ...MyCustomData })
    //}
  };
  await AdMob.prepareRewardVideoAd(options);
  const rewardItem = await AdMob.showRewardVideoAd();
}

Server-side Verification Notice

SSV callbacks are only fired on Production Adverts, therefore test Ads will not fire off your SSV callback.

For E2E tests or just for validating the data in your RewardAdOptions work as expected, you can add a custom GET request to your mock endpoint after the RewardAdPluginEvents.Rewarded similar to this:

AdMob.addListener(RewardAdPluginEvents.Rewarded, async () => {
  // ...
  if (ENVIRONMENT_IS_DEVELOPMENT) {
    try {
      const url = `https://your-staging-ssv-endpoint` + new URLSearchParams({
        'ad_network': 'TEST',
        'ad_unit': 'TEST',
        'custom_data': customData, // <-- passed CustomData
        'reward_amount': 'TEST',
        'reward_item': 'TEST',
        'timestamp': 'TEST',
        'transaction_id': 'TEST',
        'user_id': userId, // <-- Passed UserID
        'signature': 'TEST',
        'key_id': 'TEST'
      });
      await fetch(url);
    } catch (err) {
      console.error(err);
    }
  }
  // ...
});

Index

API

initialize(...)

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

Initialize AdMob with AdMobInitializationOptions

ParamTypeDescription
optionsAdMobInitializationOptionsAdMobInitializationOptions

trackingAuthorizationStatus()

trackingAuthorizationStatus() => Promise<TrackingAuthorizationStatusInterface>

Confirm requestTrackingAuthorization status (iOS >14)

Returns: Promise<TrackingAuthorizationStatusInterface>


showBanner(...)

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

Show a banner Ad

ParamTypeDescription
optionsBannerAdOptionsAdOptions

hideBanner()

hideBanner() => Promise<void>

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


resumeBanner()

resumeBanner() => Promise<void>

Resume the banner, show it after hide


removeBanner()

removeBanner() => Promise<void>

Destroy the banner, remove it from screen.


addListener(BannerAdPluginEvents.SizeChanged, ...)

addListener(eventName: BannerAdPluginEvents.SizeChanged, listenerFunc: (info: AdMobBannerSize) => void) => PluginListenerHandle
ParamTypeDescription
eventNameBannerAdPluginEvents.SizeChangedbannerAdSizeChanged
listenerFunc(info: AdMobBannerSize) => void

Returns: PluginListenerHandle


addListener(BannerAdPluginEvents.Loaded, ...)

addListener(eventName: BannerAdPluginEvents.Loaded, listenerFunc: () => void) => PluginListenerHandle

Notice: request loaded Banner ad

ParamTypeDescription
eventNameBannerAdPluginEvents.LoadedbannerAdLoaded
listenerFunc() => void

Returns: PluginListenerHandle


addListener(BannerAdPluginEvents.FailedToLoad, ...)

addListener(eventName: BannerAdPluginEvents.FailedToLoad, listenerFunc: (info: AdMobError) => void) => PluginListenerHandle

Notice: request failed Banner ad

ParamTypeDescription
eventNameBannerAdPluginEvents.FailedToLoadbannerAdFailedToLoad
listenerFunc(info: AdMobError) => void

Returns: PluginListenerHandle


addListener(BannerAdPluginEvents.Opened, ...)

addListener(eventName: BannerAdPluginEvents.Opened, listenerFunc: () => void) => PluginListenerHandle

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

ParamTypeDescription
eventNameBannerAdPluginEvents.OpenedbannerAdOpened
listenerFunc() => void

Returns: PluginListenerHandle


addListener(BannerAdPluginEvents.Closed, ...)

addListener(eventName: BannerAdPluginEvents.Closed, listenerFunc: () => void) => PluginListenerHandle

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

ParamTypeDescription
eventNameBannerAdPluginEvents.ClosedbannerAdClosed
listenerFunc() => void

Returns: PluginListenerHandle


addListener(BannerAdPluginEvents.AdImpression, ...)

addListener(eventName: BannerAdPluginEvents.AdImpression, listenerFunc: () => void) => PluginListenerHandle

Unimplemented

ParamTypeDescription
eventNameBannerAdPluginEvents.AdImpressionAdImpression
listenerFunc() => void

Returns: PluginListenerHandle


prepareInterstitial(...)

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

Prepare interstitial banner

ParamTypeDescription
optionsAdOptionsAdOptions

Returns: Promise<AdLoadInfo>


showInterstitial()

showInterstitial() => Promise<void>

Show interstitial ad when it’s ready


addListener(InterstitialAdPluginEvents.FailedToLoad, ...)

addListener(eventName: InterstitialAdPluginEvents.FailedToLoad, listenerFunc: (error: AdMobError) => void) => PluginListenerHandle
ParamType
eventNameInterstitialAdPluginEvents.FailedToLoad
listenerFunc(error: AdMobError) => void

Returns: PluginListenerHandle


addListener(InterstitialAdPluginEvents.Loaded, ...)

addListener(eventName: InterstitialAdPluginEvents.Loaded, listenerFunc: (info: AdLoadInfo) => void) => PluginListenerHandle
ParamType
eventNameInterstitialAdPluginEvents.Loaded
listenerFunc(info: AdLoadInfo) => void

Returns: PluginListenerHandle


addListener(InterstitialAdPluginEvents.Dismissed, ...)

addListener(eventName: InterstitialAdPluginEvents.Dismissed, listenerFunc: () => void) => PluginListenerHandle
ParamType
eventNameInterstitialAdPluginEvents.Dismissed
listenerFunc() => void

Returns: PluginListenerHandle


addListener(InterstitialAdPluginEvents.FailedToShow, ...)

addListener(eventName: InterstitialAdPluginEvents.FailedToShow, listenerFunc: (error: AdMobError) => void) => PluginListenerHandle
ParamType
eventNameInterstitialAdPluginEvents.FailedToShow
listenerFunc(error: AdMobError) => void

Returns: PluginListenerHandle


addListener(InterstitialAdPluginEvents.Showed, ...)

addListener(eventName: InterstitialAdPluginEvents.Showed, listenerFunc: () => void) => PluginListenerHandle
ParamType
eventNameInterstitialAdPluginEvents.Showed
listenerFunc() => void

Returns: PluginListenerHandle


prepareRewardVideoAd(...)

prepareRewardVideoAd(options: RewardAdOptions) => Promise<AdLoadInfo>

Prepare a reward video ad

ParamTypeDescription
optionsRewardAdOptionsRewardAdOptions

Returns: Promise<AdLoadInfo>


showRewardVideoAd()

showRewardVideoAd() => Promise<AdMobRewardItem>

Show a reward video ad

Returns: Promise<AdMobRewardItem>


addListener(RewardAdPluginEvents.FailedToLoad, ...)

addListener(eventName: RewardAdPluginEvents.FailedToLoad, listenerFunc: (error: AdMobError) => void) => PluginListenerHandle
ParamType
eventNameRewardAdPluginEvents.FailedToLoad
listenerFunc(error: AdMobError) => void

Returns: PluginListenerHandle


addListener(RewardAdPluginEvents.Loaded, ...)

addListener(eventName: RewardAdPluginEvents.Loaded, listenerFunc: (info: AdLoadInfo) => void) => PluginListenerHandle
ParamType
eventNameRewardAdPluginEvents.Loaded
listenerFunc(info: AdLoadInfo) => void

Returns: PluginListenerHandle


addListener(RewardAdPluginEvents.Rewarded, ...)

addListener(eventName: RewardAdPluginEvents.Rewarded, listenerFunc: (reward: AdMobRewardItem) => void) => PluginListenerHandle
ParamType
eventNameRewardAdPluginEvents.Rewarded
listenerFunc(reward: AdMobRewardItem) => void

Returns: PluginListenerHandle


addListener(RewardAdPluginEvents.Dismissed, ...)

addListener(eventName: RewardAdPluginEvents.Dismissed, listenerFunc: () => void) => PluginListenerHandle
ParamType
eventNameRewardAdPluginEvents.Dismissed
listenerFunc() => void

Returns: PluginListenerHandle


addListener(RewardAdPluginEvents.FailedToShow, ...)

addListener(eventName: RewardAdPluginEvents.FailedToShow, listenerFunc: (error: AdMobError) => void) => PluginListenerHandle
ParamType
eventNameRewardAdPluginEvents.FailedToShow
listenerFunc(error: AdMobError) => void

Returns: PluginListenerHandle


addListener(RewardAdPluginEvents.Showed, ...)

addListener(eventName: RewardAdPluginEvents.Showed, listenerFunc: () => void) => PluginListenerHandle
ParamType
eventNameRewardAdPluginEvents.Showed
listenerFunc() => void

Returns: PluginListenerHandle


Interfaces

AdMobInitializationOptions
PropTypeDescription
requestTrackingAuthorizationbooleanUse or not requestTrackingAuthorization in iOS(>14)
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').
initializeForTestingbooleanIf set to true, the devices on {@link AdMobInitializationOptions.testingDevices} will be registered to receive test production ads.
tagForChildDirectedTreatmentbooleanFor purposes of the Children's Online Privacy Protection Act (COPPA), there is a setting called tagForChildDirectedTreatment.
tagForUnderAgeOfConsentbooleanWhen using this feature, a Tag For Users under the Age of Consent in Europe (TFUA) parameter will be included in all future ad requests.
maxAdContentRatingMaxAdContentRatingWAs an app developer, you can indicate whether you want Google to treat your content as child-directed when you make an ad request.
TrackingAuthorizationStatusInterface
PropType
status'authorized' | 'denied' | 'notDetermined' | 'restricted'
BannerAdOptions

This interface extends AdOptions

PropTypeDescription
adSizeBannerAdSizeBanner Ad Size, defaults to ADAPTIVE_BANNER. IT can be: ADAPTIVE_BANNER, SMART_BANNER, BANNER, MEDIUM_RECTANGLE, FULL_BANNER, LEADERBOARD
positionBannerAdPositionSet Banner Ad position. TOP_CENTER or CENTER or BOTTOM_CENTER
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.
AdLoadInfo
PropType
adUnitIdstring
AdOptions
PropTypeDescription
adIdstringThe ad unit ID that you want to request
isTestingbooleanYou can use test mode of ad.
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.
npabooleanThe default behavior of the Google Mobile Ads SDK is to serve personalized ads. Set this to true to request Non-Personalized Ads
RewardAdOptions
PropTypeDescription
ssvAtLeastOne<{ /** * An optional UserId to pass to your SSV callback function. / userId: string; /* * An optional custom set of data to pass to your SSV callback function. */ customData: string; }>If you have enabled SSV in your AdMob Application. You can provide customData or a userId be passed to your callback to do further processing on. Important You HAVE to define one of them.
AdMobRewardItem

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

PropTypeDescription
typestringRewarded type user got
amountnumberRewarded amount user got

Type Aliases

AtLeastOne

{[K in keyof T]: Pick<T, K>}[keyof T]

Pick

From T, pick a set of properties whose keys are in the union K

{ [P in K]: T[P]; }

Enums

MaxAdContentRating
MembersValueDescription
General'General'Content suitable for general audiences, including families.
ParentalGuidance'ParentalGuidance'Content suitable for most audiences with parental guidance.
Teen'Teen'Content suitable for teen and older audiences.
MatureAudience'MatureAudience'Content suitable only for mature audiences.
BannerAdSize
MembersValueDescription
BANNER'BANNER'Mobile Marketing Association (MMA) banner ad size (320x50 density-independent pixels).
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).
MEDIUM_RECTANGLE'MEDIUM_RECTANGLE'Interactive Advertising Bureau (IAB) medium rectangle ad size (300x250 density-independent pixels).
LEADERBOARD'LEADERBOARD'Interactive Advertising Bureau (IAB) leaderboard ad size (728x90 density-independent pixels).
ADAPTIVE_BANNER'ADAPTIVE_BANNER'A dynamically sized banner that is full-width and auto-height.
SMART_BANNER'SMART_BANNER'
BannerAdPosition
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)
BannerAdPluginEvents
MembersValueDescription
SizeChanged"bannerAdSizeChanged"
Loaded"bannerAdLoaded"
FailedToLoad"bannerAdFailedToLoad"
Opened"bannerAdOpened"Open "Adsense" Event after user click banner
Closed"bannerAdClosed"Close "Adsense" Event after user click banner
AdImpression"bannerAdImpression"Similarly, this method should be called when an impression is recorded for the ad by the mediated SDK.
InterstitialAdPluginEvents
MembersValueDescription
Loaded'interstitialAdLoaded'Emits after trying to prepare and Interstitial, when it is loaded and ready to be show
FailedToLoad'interstitialAdFailedToLoad'Emits after trying to prepare and Interstitial, when it could not be loaded
Showed'interstitialAdShowed'Emits when the Interstitial ad is visible to the user
FailedToShow'interstitialAdFailedToShow'Emits when the Interstitial ad is failed to show
Dismissed'interstitialAdDismissed'Emits when the Interstitial ad is not visible to the user anymore.
RewardAdPluginEvents
MembersValueDescription
Loaded'onRewardedVideoAdLoaded'Emits after trying to prepare a RewardAd and the Video is loaded and ready to be show
FailedToLoad'onRewardedVideoAdFailedToLoad'Emits after trying to prepare a RewardAd when it could not be loaded
Showed'onRewardedVideoAdShowed'Emits when the AdReward video is visible to the user
FailedToShow'onRewardedVideoAdFailedToShow'Emits when the AdReward video is failed to show
Dismissed'onRewardedVideoAdDismissed'Emits when the AdReward video is not visible to the user anymore. Important: This has nothing to do with the reward it self. This event will emits in this two cases: 1. The user starts the video ad but close it before the reward emit. 2. The user start the video and see it until end, then gets the reward and after that the ad is closed.
Rewarded'onRewardedVideoAdReward'Emits when user get rewarded from AdReward

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.

Keywords

FAQs

Package last updated on 01 Aug 2022

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