npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nativescript/firebase-admob

v3.2.4

Published

NativeScript Firebase - Admob

Downloads

3,032

Readme

@nativescript/firebase-admob

A plugin that allows you to monetize your NativeScript app by integrating the Google Mobile Ads SDK into the app.

Note: Before you use this plugin, if you haven't already, setup your app for Firebase by following the instructions at @nativescript/firebase-core.

The @nativescript/firebase-admob plugin currently supports loading and displaying the following ad types:

Contents

Installation

To install @nativescript/firebase-admob, run the following command in the root directory of the project:

npm install @nativescript/firebase-admob

Setup Admob for iOS

Update your Info.plist file at App_Resources/iOS with a GADApplicationIdentifier key with a string value of your AdMob app ID (identified in the AdMob UI).

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>

For more information about configuring the Info.plist and setting up your App ID, see Update your Info.plist.

Setup Admob for Android

Add AdMob App ID (identified in the AdMob UI) to the app's AndroidManifest.xml file, found at App_Resources/Android/src/main. Failure to do so will result in a crash on app launch. Add the ID by adding a <meta-data> tag with name com.google.android.gms.ads.APPLICATION_ID, as shown below. For android:value insert your own AdMob App ID in quotes.

<application>
  <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
  <meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"
  />
</application>

See step 3. of Configure your app for more information about configuring AndroidManifest.xml and setting up the App ID.

Use @nativescript/firebase-admob

To use the @nativescript/firebase-admob plugin, follow the steps below:

1. Initialize the Mobile Ads SDK

Before loading ads, initialize the Mobile Ads SDK by calling the static init method on the Admob class. Call this method once, ideally right before the app boots, in the main.ts file.

import { Admob } from '@nativescript/firebase-admob'

Admob.init()

2. Add your preferred ad format to the app

The Mobile Ads SDK is now imported and you're ready to implement an ad. Click any of the links below to get detailed implementation steps for your desired ad format.

Banner ads

Banner ads are rectangular ads that appear at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period. If you're new to mobile advertising, they're a great place to start.

Testing Banner ads in development mode

Note: When developing your app, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account. Make sure you replace the test unit ID with your ad unit ID before publishing your app.

To enable dedicated test ad unit ID for banners, visit the links below:

Below are examples of adding a Banner ad in several NativeScript flavors.

Add Banner ad in NativeScript Core

Register the plugin namespace in the Page element under a prefix(ui for example), access the BannerAd view from the namespace via the prefix and add it to your XML.

The BannerAd requires the following attributes to be set:

  • unitId
  • BannerAdSize: You can set this value in the callback function of the layoutChanged event. For more information, see Customize the banner ad size
  • height and width
<Page xmlns:ui="@nativescript/firebase-admob" >

  <StackLayout>
    <ui:BannerAd
      height="100"
      width="100"
      unitId="{{bannerAdUnit}}"
      layoutChanged="{{bannerLoaded}}"
/>
  </StackLayout>

Add Banner ad in NativeScript Angular

Register the BannerAd view by adding its AdmobModule to the imports array of the @NgModule decorator of the component where you want to use the view.

import { AdmobModule } from '@nativescript/firebase-admob/angular';

@NgModule({
    imports: [
    AdmobModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})

Next, add the BannerAd view to HTML. The BannerAd requires the following attributes to be set:

  • unitId
  • BannerAdSize: You can set this value in the callback function of the layoutChanged event. For more information, see Customize the banner ad size
  • height and width
<BannerAd
  height="100"
  width="100"
  [unitId]="bannerAdUnit"
  (layoutChanged)="bannerLoaded($event)">
</BannerAd>

Add Banner ad in NativeScript Vue

Register the BannerAd view in the app.ts file as follows:

import { createApp } from 'nativescript-vue';
import Admob from '@nativescript/firebase-admob/vue'
import Home from './components/Home.vue';

const app = createApp(Home)
app.use(Admob)

And then add it to markup as follows. The BannerAd requires the following attributes to be set:

  • unitId
  • BannerAdSize: You can set this value in the callback function of the layoutChanged event. For more information, see Customize the banner ad size
  • height and width
<BannerAd
  height="100"
  width="100"
  :unitId="bannerAdUnit"
  @layoutChanged="bannerLoaded"/>

Customize the banner ad size

To define a custom banner size, you have 2 options:

  • Instantiate the BannerAdSize class with the desired width and height and set it to the size attribute of BannerAd.
import { BannerAdSize } from "@nativescript/firebase-admob"

const adSize = new BannerAdSize(300, 50)

banner.size = adSize
  • Set the size to any of the constants of the BannerAdSize class.

The table below lists the available constants and the sizes they represent.

| AdSize Constant | Size in dp (WxH) | Description |:---------------|:--------------|:--------------- | BANNER | 320x50 | Standard Banner | LARGE_BANNER | 320x100 | Large Banner
| MEDIUM_RECTANGLE | 320x250 | Medium Rectangle | FULL_BANNER | 468x60 | Full-Size Banner
| LEADERBOARD | 728x90 | Leaderboard
| createAnchoredAdaptiveBanner(width, orientation)| Provided width x Adaptive height | Adaptive Banner
| createInLineAdaptiveBanner(width, orientation) | Provided width x Adaptive height | Adaptive Banner

Listen to a banner ad lifecycle events

The plugin enables you to listen to different lifecycle events of an ad, such as when an ad is loaded. Register the events handlers before calling the load method.

const bannerView = event.object;

// Called when an ad is successfully received.
bannerView.on('adLoaded', (args) =>{
console.log('Ad loaded.'),
});

 // Called when an ad request failed.
bannerView.on('adFailedToLoad', (args) =>{
   console.log('Ad failed to load: ', args.error);
});

 // Called when the user removes an overlay that covers the screen.
bannerView.on('adClosed', (args) =>{
   console.log('Ad closed.');
});

 // Called when an impression occurs on the ad.
bannerView.on('adImpression', (args) =>{
   console.log('Ad impression.');
});

 // Called when an tap/touch/click occurs on the ad.
bannerView.on('adClicked', (args) =>{
   console.log('Ad tapped');
});

Display a banner ad to the user

To display a banner ad to the user, get the reference to the BannerAd view and call the load method on it.

bannerView.load()

Add an Interstitial ad

Interstitial ads are full-screen ads that cover the interface of an app until closed by the user. They're best used at natural pauses in the flow of an app's execution, such as between levels of a game or just after a task is completed.

Testing Interstitial ads in development

Note: When your app is in development mode, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account. Make sure you replace the test unit ID with your ad unit ID before publishing your app. To enable dedicated test ad unit ID, visit the links below:

Display an Interstitial ad to the user

To display an Interstitial ad to the user, follow the steps below:

  1. Import the InterstitialAd class from @nativescript/firebase-admob.
import { InterstitialAd } from '@nativescript/firebase-admob'
  1. Create an Interstitial ad instance.

Create an Interstitial ad instance by calling the static createForAdRequest on the class. The createForAdRequest method requires an adUnitId and you can optionally pass a RequestOptions object.

import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-3940256099942544/4411468910')
  1. Listen to the ad lifecycle events

To listen for the ad lifecycle events, such as when the ad is display or dismissed, call the onAdEvent method on the ad instance, before displaying the ad, passing it a callback function to handle the events.

import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-3940256099942544/4411468910')

ad.onAdEvent((event, error, data) => {
  switch (event) {
    case AdEventType.LOADED:
      break
    case AdEventType.CLOSED:
      break
    case AdEventType.OPENED:
      break
    case AdEventType.IMPRESSION:
      break
    case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
      break
  }
})
  1. Load the ad You load the ad by calling the load method on the ad instance.
import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-3940256099942544/4411468910')

ad.onAdEvent((event, error, data) => {
  switch (event) {
    case AdEventType.LOADED:
      break
    case AdEventType.CLOSED:
      break
    case AdEventType.OPENED:
      break
    case AdEventType.IMPRESSION:
      break
    case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
      break
  }
})

ad.load()
  1. Display the the ad

To display the ad, call the show method on the ad instance. This method is called after the load method.

import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-3940256099942544/4411468910')

ad.onAdEvent((event, error, data) => {
  switch (event) {
    case AdEventType.LOADED:
      break
    case AdEventType.CLOSED:
      ad.show()
      break
    case AdEventType.OPENED:
      break
    case AdEventType.IMPRESSION:
      break
    case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
      break
  }
})

ad.load()

Next steps

Native Ads

Native ads are ad assets that are presented to users via UI components that are native to the platform. They're shown using the same types of views with which you're already building your layouts, and can be formatted to match the visual design of the user experience in which they live. In coding terms, this means that when a native ad loads, your app receives a NativeAd object that contains its assets, and the app (rather than the Google Mobile Ads SDK) is then responsible for displaying them.

Adding a Native ad in NativeScript Core

To add a Native ad to your {N} Core app, follow these steps:

  1. Register the plugin namespace under a prefix, ui (this can be any name), with the Page element.
<Page xmlns:ui="@nativescript/firebase-admob" >

</Page>
  1. Use the prefix to access the NativeAdView and add it to markup.
<Page xmlns:ui="@nativescript/firebase-admob" >
<ActionBar title="Admob" />
<StackLayout>

  <ui:NativeAdView height="400" loaded="{{nativeAdLoaded}}" />

</StackLayout>
</Page>

Testing Native ads in development mode

Note: When developing your app, make sure you use test ad unit IDs rather than live, production ads. Failure to do so can lead to suspension of your account. Just make sure you replace the test ad unit ID with your own ad unit ID before publishing your app.

To enable dedicated test ad unit ID, visit the links below:

  1. Import the NativeAdLoader class from @nativescript/firebase-admob in the view model file.
import { NativeAdLoader } from '@nativescript/firebase-admob'

The NativeAdLoader class is an interface for managing the the Native ad.

  1. Instantiate NativeAdLoader. Create an instance of NativeAdLoader by calling its constructor function. The constructor function accepts 3 parameters. The required adUnitId as the first parameter, optional RequestOptions and NativeAdOptions objects as the second and third parameter, respectively.
const loader = new NativeAdLoader('ca-app-pub-3940256099942544/3986624511', null, {
  nativeAdOptions: {
    adChoicesPlacement: AdChoicesPlacement.TOP_RIGHT
  }
})
  1. Listen to the Native ad lifecycle events

To listen to the Native ad lifecycle events, call the onAdEvent method on the NativeAdLoader instance when the NativeAdView has loaded.

<ui:NativeAdView height="400" loaded="{{ nativeAdLoaded }}">
  <GridLayout height="300" width="300">
    <Label id="headLineView" />
    <ui:MediaView id="mediaView" height="100%"/>
    <Label id="bodyView" />
    <Button id="callToActionView" />
  </GridLayout>
</ui:NativeAdView>
nativeAdLoaded(event){
const view = event.object;
loader.onAdEvent((event, error, data) => {
	if (event === NativeAdEventType.LOADED) {
		const ad = data as NativeAd;

		const headLineView = view.getViewById('headLineView');
		headLineView.text = ad.headline;
		const mediaView = view.getViewById('mediaView');
		view.mediaView = mediaView;
		mediaView.mediaContent = ad.mediaContent;
		const callToActionButton = view.getViewById('callToActionView');
		view.callToActionView = callToActionButton;
		callToActionButton.text = ad.callToAction;
		const bodyView = view.getViewById('bodyView');
		bodyView.text = ad.body;
		view.nativeAd = ad;
		console.log('nativead loaded');
	} else if (event === 'adFailedToLoad') {
		console.log('nativead failed to load', error);
	}
});
}
  1. Display the Native ad To display the Native ad, call the load method on a NativeAdLoader instance.
loader.load()

NativeAdOptions interface

A NativeAdOptions object is used to set the following options on the native ad. | Property | Type | Description |:---------|:-----|:----------- | returnUrlsForImageAssets | boolean | Optional: If set to true, the SDK will not load image asset content and native ad image URLs can be used to fetch content. Defaults to false. | multipleImages | boolean| Optional: Some image assets contain a series of images. Setting this property to true tells the app to display all the images of an asset. The false(the default) value informs the app to display the first image from the series of images in an image asset. | adChoicesPlacement | AdChoicesPlacement |Optional: The AdChoices overlay is set to the top right corner by default. Apps can change which corner this overlay is rendered in by setting this property to one of the following: | videoOptions | videoOptions| Optional: Used to set video options for video assets returned as part of a native ad. If an ad contains a video(if ad.mediaContent.hasVideoContent = true), display the video. | mediaAspectRatio | MediaAspectRatio | Optional: This sets the aspect ratio for image or video to be returned for the native ad.

AdChoicesPlacement

enum AdChoicesPlacement {
	TOP_LEFT = 'topLeft',
	TOP_RIGHT = 'topRight',
	BOTTOM_RIGHT = 'bottomRight',
	BOTTOM_LEFT = 'bottomLeft',
}

videoOptions

The videoOptions property is an object with the following properties: | Property | Type | Optional |:---------|:----|:------- | startMuted | boolean | Yes | clickToExpandRequested | boolean | Yes | customControlsRequested | boolean | Yes

MediaAspectRatio

enum MediaAspectRatio {
	LANDSCAPE = 'landscape',
	PORTRAIT = 'portrait',
	SQUARE = 'square',
	ANY = 'any',
}

That's it! Your app is now ready to display native ads.

Next steps

Rewarded Ads

Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards.

Testing Rewarded ads in development mode

Note: When developing your app, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account. Make sure you replace the test unit ID with your ad unit ID before publishing your app.

To enable dedicated test ad unit ID, visit the links below:

Display a Rewarded ad

Follow these steps to display a Rewarded ad:

  1. Import the RewardedAd class from @nativescript/firebase-admob.
import { RewardedAd } from '@nativescript/firebase-admob'
  1. Create a RewardedAd instance

Create a Rewarded ad instance by calling the createForAdRequest static method on the RewardedAd class and passing it the ad unit id.

import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-3940256099942544/1712485313')
  1. Listen to the ad lifecycle events Before you call the load method to load the ad, call the onAdEvent method passing it a callback function to handle the ad events.
import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-3940256099942544/1712485313')

ad.onAdEvent((event, error, data) => {
  if (event === AdEventType.LOADED) {
    console.log('rewarded', 'loaded')
  } else if (event === AdEventType.FAILED_TO_LOAD_EVENT) {
    console.error('loading error', error)
  }
})
  1. Load the ad To load the ad, call the load method on the RewardAd instance.
import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-3940256099942544/1712485313')

ad.onAdEvent((event, error, data) => {
  if (event === AdEventType.LOADED) {
    console.log('rewarded', 'loaded')
  } else if (event === AdEventType.FAILED_TO_LOAD_EVENT) {
    console.error('loading error', error)
  }
})
ad.load()
  1. Display the ad

To show the ad on the screen, call the show() method on the ad instance.

import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-3940256099942544/1712485313')

ad.onAdEvent((event, error, data) => {
  if (event === AdEventType.LOADED) {
      console.log('rewarded', 'loaded')
      ad.show()
  } else if (event === AdEventType.FAILED_TO_LOAD_EVENT) {
    console.error('loading error', error)
  }
})
ad.load()

Rewarded ad Events

RewardAd emits the following lifecycle events that you can listen to:

ad.onAdEvent((event, error, data) => {
  switch (event) {
    case AdEventType.LOADED:
      break
    case AdEventType.CLOSED:
      break
    case AdEventType.OPENED:
      break
    case AdEventType.IMPRESSION:
      break
    case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
      break
  }
})

onAdEvent with the event rewarded_earned_reward'is invoked when the user earns a reward. Be sure to implement this and reward the user for watching an ad.

Targeting

The RequestConfiguration object collects the global configuration for every ad request and is applied by firebase().admob().setRequestConfiguration().

Child-directed ads setting

For child-directed ads setting, read Child-directed setting.

The following example indicates that you want your content treated as child-directed for purposes of COPPA:

import { Admob, RequestConfiguration } from '@nativescript/firebase-admob';
const requestConfiguration: RequestConfiguration = {
  tagForChildDirectedTreatment: true
}
Admob.getInstance().requestConfiguration = requestConfiguration;

Handle ads requests for users under the age of consent

To handle ads requests for users under the age of consent, read Users under the age of consent.

The following example indicates that you want TFUA included in your ad request.

import { Admob, RequestConfiguration } from '@nativescript/firebase-admob';
const requestConfiguration: RequestConfiguration = {
  tagForUnderAgeOfConsent: true
}
Admob.getInstance().requestConfiguration = requestConfiguration;

If the tags to enable the Child-directed setting and tagForUnderAgeOfConsentare both set to true, the child-directed setting takes precedence.

Ad content filtering

This setting can be set via RequestConfiguration.maxAdContentRating:

AdMob ads returned for these requests have a content rating at or below that level. The possible values for this network extra are based on digital content label classifications, and should be one of the following MaxAdContentRating objects:

  • MaxAdContentRating.G
  • MaxAdContentRating.PG
  • MaxAdContentRating.T
  • MaxAdContentRating.MA

The following code configures a RequestConfiguration object to specify that an ad content returned should correspond to a digital content label designation no higher than G:

import { Admob, MaxAdContentRating, RequestConfiguration } from '@nativescript/firebase-admob';
const requestConfiguration: RequestConfiguration = {
  maxAdContentRating: MaxAdContentRating.G
}
Admob.getInstance().requestConfiguration = requestConfiguration;

License

Apache License Version 2.0