Skip to content

Cordova first steps

Marc Pascual edited this page Jun 29, 2020 · 10 revisions

First steps

Android & iOS mobile apps

When working on an android or ios device, keep in mind that the plugin will be available only after deviceready event. The plugin is accessible from window object: window.admob.

The ad ids used in the example code are should be used only for development and test purposes. If you do not replace them with your own ones, please ensure to always use the isTest option set to true.

Javascript

async function onDeviceReady() {
    await admob.createBannerView({
        bannerAdId: 'ca-app-pub-3940256099942544/6300978111',
    });
}

document.addEventListener('deviceready', this.onDeviceReady, false);

Angular

import { Component, OnInit } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Admob } from '@ionic-native/admob/ngx';

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
})
export class HomePage implements OnInit {
    constructor(private admob: Admob, private platform: Platform) { }

    async ngOnInit() {
        await this.platform.ready();
        await this.admob.createBannerView({
            bannerAdId: 'ca-app-pub-3940256099942544/6300978111',
        });
    }
}

Angular is referring to Angular v2 version and newer. For AngularJS (Angular v1) see this example

Web browser

If you are using a browser platform, the plugin will be available in the window object. Note that the deviceready event will not be fired in browsers and the plugin will be immediately available after page has loaded.

In browser AdSense will be used instead of AdMob. Make sure to properly configure it:

Javascript

async function initAds() {
    var options = {
            publisherId: 'ca-app-pub-XXXXXXXXXXXXXXXX', // AdSense
            adSlot: 'BBBBBBBBBB', // AdSense
        };
    var admob = window.admob;
    await admob.createBannerView(options);
}
initAds();

Angular

import { Component, OnInit } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Admob } from '@ionic-native/admob/ngx';

@Component({
    selector: 'app-home',
    templateUrl: 'home.html',
})
export class HomePage implements OnInit {

    private admob: Admob;

    constructor(private platform: Platform) { }

    async ngOnInit() {
        const cordovaWindow = window as any;
        this.admob = cordovaWindow.admob as Admob;

        const options = {
            publisherId: 'ca-app-pub-XXXXXXXXXXXXXXXX', // AdSense
            adSlot: 'BBBBBBBBBB', // AdSense
        };
        await this.admob.createBannerView(options);
    }
}