Search code examples
cordovaionic-frameworkionic2ionic3cordova-plugins

Property 'cordova' does not exist on type 'Window'. : ionic


In my code, I'm getting the error as Property 'cordova' does not exist on type 'Window'. This is where I'm getting the error var browserRef = window.cordova.InAppBrowser.open()

I've also installed the typings but still I'm getting this error. How can I resolve this?


Solution

  • That's just Typescript complaining because cordova is not part of the window object definition. There're several ways to avoid that error:

    One way is to declare a window property of type any, like this:

    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    
    declare let window: any; // <--- Declare it like this
    
    @Component({
      selector: 'page-demo',
      templateUrl: 'demo.html'
    })
    export class DemoPage {
    
      constructor(public navCtrl: NavController, ...) { }
    
      public yourMethod(): void {
        var browserRef = window.cordova.InAppBrowser.open(); // <--- and use it like this
      }
    
    }
    

    Another way would be to cast the window object to be of type any in the same statement where you want to use it:

    var browserRef = (<any>window).cordova.InAppBrowser.open();
    // or
    var browserRef = (window as any).cordova.InAppBrowser.open();
    

    If you don't want to use any you could also define the type of the window object based on the method/s you want to call:

    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    
    declare let window: {
      cordova: {
        InAppBrowser: {
          open: () => {};
        }
      }
    }
    
    @Component({
      selector: 'page-demo',
      templateUrl: 'demo.html'
    })
    export class DemoPage {
    
      constructor(public navCtrl: NavController, ...) { }
    
      public yourMethod(): void {
        var browserRef = window.cordova.InAppBrowser.open();
      }
    
    }