Property 'cordova' does not exist on type 'Window'. : ionic
Solution 1
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();
}
}
Solution 2
Cordova executes only on devices, not in browser. The way to avoid errors when viewing your build in a browser is to wrap Cordova commands in a platform if statement. In example:
import { Platform } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
constructor( private platform: Platform, private iab: InAppBrowser ) {
this.platform.ready().then(function () {
if (platform.is('cordova')) {
// your code, eg:
this.iab.create('http://google.com/', '_blank');
}
});
}
Solution 3
Another solution would be to change
window.cordova
to
window['cordova']
Solution 4
In typescript 4, tslint doesn't like the <any>
cast anymore.
It seems to now prefer this.
var browserRef = (window as any).cordova.InAppBrowser.open();
Admin
Updated on June 09, 2022Comments
-
Admin almost 2 years
In my code, I'm getting the error as
Property 'cordova' does not exist on type 'Window'.
This is where I'm getting the errorvar browserRef = window.cordova.InAppBrowser.open()
I've also installed the
typings
but still I'm getting this error. How can I resolve this? -
Admin over 5 yearsyes, I have done the same but still, I get the error. this error is showing by vs code IDE & well as in browser when I run the command
ionic serve
. I have another ionic project where I have used the same code but I don't have any issue there. -
Admin over 5 yearsI have used
declare var window: any;
and it solved my problem. -
muttonUp about 3 yearsSee my answer below for a tslint safe version for TS 4