Accessing external cordova plugin


#1

Hello,

For few days I’m struggling with adding cordova plugins to my Ionic2 application. I tried several plugins and I always get the same error. Having the plugin added to my project (I used ionic plugin add command) with a clobbers content like below:

<js-module src="plugin/www/pushmote.js" name="Pushmote">
    <clobbers target="Pushmote" />
</js-module>

my understanding is that I should be able to use that plugin just with window.Pushmote:

import {Page} from 'ionic-angular';

@Page({
  templateUrl: 'build/pages/page3/page3.html'
})
export class Page3 {
  constructor() {
    window.Pushmote.startWithApplicationId(...);
  }
}

Is that correct?

Unfortunately, it doesn’t work:

Error TS2339: Property ‘Pushmote’ does not exist on type ‘Window’.

This is not only about Pushmote plugin - it’s just a next random plugin I’ve tried to incorporate into my project with no success. I’m still getting exactly the same error. What am I doing wrong?

I’ve read this thread: Ionic 2 and custom plugin and looks that theoretically I’m doing everything correctly, so what is wrong?


#2

Don’t fall in love with this technique, because it subverts TypeScript’s typing system, but when you have badly behaving modules that pollute the global namespace like this, the simplest way to handle it is:

(<any>window).Pushmote.startWithApplicationId(...);

#3

So what’s the ideal way for plugin to register itself? I’ve looked at the source code of several plugins and all of them do
module.exports = mymodule
and some of them do additionally
window.mymodule = ...


#4

You can check out the ionic-native source code to see how other plugins have been made user-friendly.


#5

Thank you for help.

Yet one question. With (<any>window).Pushmote I have everything working fine in android simulator. However, if I run ionic serve, (<any>window).Pushmote is undefined. I see it for every single plugin I try to access through <any>window. Is this expected behaviour? Is there any workaround?


#6

Yes.

Depends on the plugin. Generally, no. Most plugins require a device environment.


#7

Everything is clear now for me. Thanks!