Ionic InAppBrowser. Not always working - android

I currently have an Ionic app that creates an InAppBrowser pointing to a Website. I have deployed it to my Android phone, however there is a big issue.
Sometimes the app doesn’t work and opens the website with my default browser. Sometimes it does work and opens the website in the app using InAppBrowser.
I have tried using the different targets self, blank, system and different Android phones, but nothing fully works.
I am really confused and tried a number of things, any ideas?
Thanks in advance.
Below are my code files:
home.html
<ion-header>
<ion-navbar color="dark">
<ion-title>
InAppBrowser
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
InAppBrowser Not Displayed.
</ion-content>
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser, InAppBrowserOptions } from "#ionic-native/in-app-browser";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, private inAppBrowser: InAppBrowser) {
const options: InAppBrowserOptions = {
toolbar: 'no',
location: 'no',
zoom: 'no'
}
const browser = this.inAppBrowser.create("https://www.awebsite.co.uk", '_self', options);
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { InAppBrowser } from '#ionic-native/in-app-browser';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
InAppBrowser
]
})
export class AppModule {}

Did you try to wait the "platform" to be "ready" to use?
https://ionicframework.com/docs/api/platform/Platform/
export class HomePage {
constructor(public navCtrl: NavController, private inAppBrowser: InAppBrowser, public platform: Platform) {
const options: InAppBrowserOptions = {
toolbar: 'no',
location: 'no',
zoom: 'no'
}
this.platform.ready().then( () => {
const browser = this.inAppBrowser.create("https://www.awebsite.co.uk", '_self', options);
})
}
}
Doing this, the code will only run when the app is ready. In the device environment, when Cordova is ready to be used.

Related

Ionic 4 fails to load on mobile once i add Google Firebase to the project

My ionic 4 project works great on chrome, devapp and even after compiling to apk.
But once I add firebase config it fails to load using both devapp or even after compiling to apk.
here is how I add firebase:
first of all, I install it using npm install #angular/fire firebase --save
My environments.ts it looks like:
export const environment = {
production: false,
firebase: {
apiKey: 'xxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxx.firebaseapp.com',
databaseURL: 'https://xxxxxxxxxxxxxx.firebaseio.com',
projectId: 'xxxxxxxxxxxxxxx',
storageBucket: 'xxxxxxxxxxxxxx.appspot.com',
messagingSenderId: 'xxxxxxxxxxxxxxx'
}
};
then I add these lines with trailing <<<< to my app.module.ts :
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { environment } from '../environments/environment'; <<<<
import { AngularFireModule } from '#angular/fire'; <<<<<
import { AngularFirestoreModule } from '#angular/fire/firestore'; <<<<
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase), <<<<
AngularFirestoreModule <<<<
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
once I finish this, the app is no longer working on mobile ( white death screen)
And that is what I get when I use the chrome remote dev. tools:
Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

Ionic Android Issue: scan function not working

I am new to angularjs and ionic cordova. I am following the code given in this video lecture on ionic cordova BLE plugin module. I am trying to make this work using ionic 3 and have installed ionic cordova plugin for BLE.
https://www.youtube.com/watch?v=chfXawb_eVY&t=1898s
I have followed the exact instruction. Here's are my code files:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { BLE } from '#ionic-native/ble';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
BLE
]
}) export class AppModule {}
home.ts
import { Component, NgZone } from '#angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '#ionic-native/ble';
import { ToastController } from 'ionic-angular';
import { setTimeout } from 'core-js/library/web/timers';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
devices: any[] = [];
statusMessage:string;
constructor(public navCtrl: NavController,
public toastCtrl: ToastController,
private ble: BLE,
private ngZone: NgZone) {
}
scan(){
this.setStatus('Scanning for bluetooth LE devices');
this.devices = [];
this.ble.scan([], 2).subscribe(
device=>this.onDeviceDiscovered(device),
error=>this.scanError(error)
);
setTimeout(this.statusMessage.bind(this),5000,'Scan Complete');
}
onDeviceDiscovered(device){
console.log('Scanning');
console.log('Discovered ' + JSON.stringify(device,null,2));
this.ngZone.run(()=>{
this.devices.push(device);
});
}
scanError(error) {
console.log('Check your bluetooth connection');
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
BLE Scanner
</ion-title>
<ion-buttons end>
<button ion-button (click)="scan()">
Scan
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item *ngFor="let device of devices">
<h2>{{ device.name || 'Unnamed' }}</h2>
<p>{{ device.id }}</p>
<p>RSSI:{{ device.rssi }}></p>
</button>
</ion-list>
</ion-content>
The function scanError is not written in the video, I have wrote it.
This is the webview screenshot
this.setStatus function is not defined. However, in the video, the function has not been declared. I tried by declaring
setStatus:any
but the function still displayed the same message. Also, I am not able to get any messages in the console even if I remove the setStatus function.
I have included NgZone component at the beginning.
Is there any way to get this resolved or am I missing something?
You need to write a setStatus function in your code.
setStatus(message) {
console.log(message);
this.ngZone.run(() => {
this.statusMessage = message;
});
}
The code on the slides is abbreviated. The source code for the examples in the presentation is available on github https://github.com/don/ionic-ble-examples

Angular Cordova -> local http.get call always fails if routed to in android cordova

I am trying to load a local json file into my service component to fill a template with it. The http call works always in my browser but bundled with cordova it only works if I use the tag directly instead of with the routing module. :S
in my nav component I got
ngOnInit() {
alert('enter on init')
this.chatService.getJSON().subscribe(data => {
this.Questionaire = data;
console.log('fill Questionaire');
console.log(this.Questionaire.UserChatContent);
this.createNewItem(this.Questionaire);
}, err => {
console.log('error');
err.forEach(e => alert(e) );
});
console.log('leave on init');
}
this is my routing module
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import {ChatViewComponent} from './chat-view/chat-view.component';
import {DailyTrainingComponent} from './daily-training/daily-training.component';
import {HttpClient, HttpClientModule} from '#angular/common/http';
const routes: Routes = [
{ path: 'chat', component: ChatViewComponent },
{ path: 'training', component: DailyTrainingComponent }
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
now the Issue:
//the following code works fine in cordova on android
//and in my browser window (firefox and chrome)
<div class="fullScreen">
<app-chat-view></app-chat-view>
</div>
whereas
// works in browser like its supposed to
// but in cordova on android the http call in the ngOnInit() in the component always fails :S
<div class="fullScreen">
<nav id="navStyle">
<a class="navElem" routerLink="/fd" (click)="navActive(0)"><div class="navOne"></div></a>
<a class="navElem" routerLink="/training" (click)="navActive(1)"><div class="navTwo"></div></a>
<a class="navElem" routerLink="/chat" (click)="navActive(2)"><div class="navChat"></div></a>
<a class="navElem" routerLink="/df" (click)="navActive(3)"><div class="navFour"></div></a>
<a class="navElem" routerLink="/d" (click)="navActive(4)"><div class="navFive"></div></a>
</nav>
<router-outlet></router-outlet>
</div>
I am new to angular 5 so I really hope this is not a stupid question. :S
thanks in advance :D
(here the service I am using HttpClient and HttpClientModule)
import { Injectable } from '#angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpClient, HttpClientModule} from '#angular/common/http';
#Injectable()
export class ChatService {
Questionaire: object;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
alert('Object: ' + data.UserChatContent);
this.Questionaire = data;
});
}
public getJSON(): Observable<any> {
return this.http.get('./assets/questionaire.json');
}
}

ionic3/angular4 Lazy loading Don't work

CLI:
node -v 6.11.2
cordova -v 6.5.0
ionic -v 3.9.2
Create an ionic tabs project with only the homepage(Manually deleted):
ionic start demo1 tabs
then create two pages use the cmd:
ionic g page Oneself
ionic g page Setting
this is app.module.ts code:
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
//import { SettingPage } from "../pages/setting/setting";
//import { OneselfPage } from "../pages/oneself/oneself";
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
#NgModule({
declarations: [
MyApp,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
this is oneself.module.ts like this:
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { OneselfPage } from './oneself';
#NgModule({
declarations: [
OneselfPage,
],
imports: [
IonicPageModule.forChild(OneselfPage),
],
exports:[
OneselfPage
]
})
export class OneselfPageModule {}
this is oneself.ts File Code like this:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
/**
* Generated class for the OneselfPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-oneself',
templateUrl: 'oneself.html',
})
export class OneselfPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad OneselfPage');
}
}
SettingPage Same as above;
this is tabs.ts code :
import { Component } from '#angular/core';
import { HomePage } from '../home/home';
#Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tab1Root = HomePage;
tab2Root = "OneselfPage";//class name
tab3Root = "SettingPage";//class name
constructor() {
}
}
I know that lazy loading has several key points, such as declaring #ionicpage (), #ngmodule, IonicPageModule. ForChild (pageName)... I have such declarations in my code, but lazy loads don't work and the errors are as follows:
This is the first line error, and I don't know if it's related to lazy loading
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
The following error must have something to do with lazy loading :
Error {rejection: Error, promise: t, zone: r, task: t, stack: <accessor>, …}
message: "Uncaught (in promise): Error: Cannot find module '../pages/oneself/oneself.module'.
Error: Cannot find module '../pages/oneself/oneself.module'
at file:///android_asset/www/build/main.js:65357:9
at t.invoke
See screen capture :
https://i.stack.imgur.com/AGTVN.jpg
Can someone help me answer this question?
Problem solved, the cordova ionic installed with cnpm has the problem,dont use cnpm install , use npm install ,the lazy load is run.
CLI:
node -v 8.2.1
cordova -v 7.0.1
ionic -v 3.9.2
I have followed what you have described
ionic start demo1 tabs
ionic g page Oneself
ionic g page Setting
I was unable to reproduce any of the errors that you were stating
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
or
Error {rejection: Error, promise: t, zone: r, task: t, stack: <accessor>, …}
message: "Uncaught (in promise): Error: Cannot find module '../pages/oneself/oneself.module'.
Error: Cannot find module '../pages/oneself/oneself.module'
at file:///android_asset/www/build/main.js:65357:9
at t.invoke
If you want to compare against my reproduction of your scenario you can do so, hope this helps

Open a file within the app folder with fileOpener Ionic2

this is my code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FileOpener } from 'ionic-native';
#Component({
selector: 'page-installHelper',
templateUrl: 'installHelper.html'
})
export class InstallHelper {
constructor(public navCtrl: NavController) {
FileOpener.open('assets/app.apk', 'application/vnd.android.package-archive').then(
function(){
console.log("success");
}, function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}
}
but I can't access the file app.apk which is in assets/app.apk
and I get the error :
Status : 9
Error : File Not Found
is it even possible to access a file within the app folders ?
Well I did it by making the app get downloaded from a server to a local folder I created in the phone and install it immediately/automatically,
Here is the code in case someone else needed it one day :
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { FileOpener } from 'ionic-native';
import { File } from 'ionic-native';
import { Transfer } from 'ionic-native';
import { HomePage } from '../pages/home/home';
declare var cordova: any;
#Component({
template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage = HomePage;
constructor(platform: Platform, public loadingCtrl: LoadingController) {
let me = this;
platform.ready().then(() => {
let loading = me.loadingCtrl.create({
content: 'Preparing The App ...'
});
loading.present();
File.createDir(cordova.file.externalDataDirectory, "appFolder", true).then(function(link){
const fileTransfer = new Transfer();
let url = 'http://yourserverhere.com/app.apk';
fileTransfer.download(url, cordova.file.externalDataDirectory +"appFolder/app.apk").then((entry) => {
loading.dismiss();
FileOpener.open(entry.toURL(), "application/vnd.android.package-archive").then(
function(){
console.log("success");
},function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}, (error) => {
console.log(error);
});
},function(error){
console.log(error);
});
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
Any explanation just ask me.
Well since you want the user to download the .apk file, you could use (in your html)
<a href="assets/app.apk" download>Download apk</a>
But the user will have to manually open his downloads (or tap the popup) to install your app.
I do not know if there is a plugin which is capable of installing these apk files. (Googling for ionic 2 install external apk didn't return any results).

Categories

Resources