Ionic 3 The external links open only once in system browser outside in appbrowser - ionic-framework

i wrapped a website and there are external links which i made to open in System browser, but when I return to in-app browser using hardware back button and again try to open the external links it doesn’t open. It looks like the 'loadstart" occurs only once.Or am i doing anything wrong here?
home.ts
export class HomePage {
constructor(public navCtrl: NavController, private iab: InAppBrowser, public
platform: Platform,private fileOpener: FileOpener, private
transfer:FileTransfer, private file: File, private diagnostic:Diagnostic) {
platform.ready().then(() => {
const browser =
this.iab.create('https://www.tutorialspoint.com/ionic/index.htm','_blank',
{zoom:'yes',location:'no', clearcache: 'yes', clearsessioncache: 'yes'});
browser.show();
browser.on('loadstart').subscribe(
(data) => {
console.log("URL IS", data.url);
this.downloadfile(data.url)
},
err => {
console.log("InAppBrowser Loadstop Event Error: " + err);
}
);
});
}
downloadfile(url) {
var externalCheck = (!url.includes("tutorial.points"));
var pdfCheck = (url.substr(url.length - 4) == '.pdf');
if (externalCheck || pdfCheck) {
window.open(url, "_system", 'location=no');
}
}
}
Is there any solution for this ? any help is really appreciated.Thanks in advance

Related

Runtime Error : Cannot read property 'push' of undefined

am trying to redirect the page in ionic3. I have used this.navCtrl.push(TemplesPage); but it is showing error "Runtime Error: Cannot read property push of undefined". please help me on this.
Thanks
ngOnInit(){
this.task = setInterval(function () {
this.navCtrl.push(TemplesPage);
}, 3000);
}
When the app open first it displays logo, after 3 seconds it redirects to home page, this is what am trying to develop.
Try like this method. I hope it fix.[Ionic 3]
import { NavController } from 'ionic-angular';
import { HomePage } from '/home';
class MyComponent {
constructor(public navCtrl: NavController) {
}
openOtherPage(){
setTimeout(() => {
this.navCtrl.push(HomePage)
}, 5000);
}
}

Ionic InAppBrowser and routes

I am working on an ionic project.
I need to use the InAppBrowser plugin to display a website.
But depending on which page I am, I need to change the view to an Ionic page.
export class HomePage {
constructor(public navCtrl: NavController, public inAppBrowser: InAppBrowser, public platform: Platform) {
var url = "https://helloworld.com";
var browser = inAppBrowser.create(url, '_blank', {
zoom: 'no',
location: 'no'
});
platform.ready().then(() => {
browser.show();
browser.on('loadstart').subscribe((e) => {
var navCtlr = this.navCtrl;
var scriptUrlParam = "window.addEventListener(\"click\",function(e){var href=e.target.getAttribute(\"href\");if(href){location.href=href+\"?source=mobapp\";e.preventDefault();}});";
var url = e.url;
if (url.indexOf("scanner") !== -1) {
alert("Page Scanner");
navCtrl.push(QrcodePage);
}
browser.insertCSS({
code: "#mobileMenu{display:block!important;}"
});
browser.executeScript({
code: scriptUrlParam
});
});
});
}
}
navCtrl.push(QrcodePage); is supposed to redirect me to the QR Code page. But it doesn't work.
I know I am on the right page because alert("Page Scanner"); is working.
Have anyone occurred this probleme already ?
Thanks

Events in Ionic v4

I'm using Ioni v4Beta and I'm traying to update the sidemenu when the user is login.
I search but the usual solution is use Events:
Ionic 3 refresh side menu after login
https://ionicframework.com/docs/api/util/Events/
But in the new version I don't find it, and I don't know how to do it
https://beta.ionicframework.com/docs/api
Thanks a lot, but I finally find how to import it:
import { Events } from '#ionic/angular';
Example on how to do it with subjects:
export const someEvent:Subject = new Subject();
export class ReceivingClass implements OnDestroy, OnInit
{
private someEventSubscription:Subscription;
public OnInit():void{
someEventSubscription = someEvent.subscribe((data) => console.log(data);
}
public onDestroy():void{
someEvent.unsubscribe();
}
}
export class SendingClass implements OnInit
{
public OnInit():void{
setTimeout(() => {
someEvent.next('hi');
}, 500);
}
}
Are you aware that Ionic v4 events will be deprecated soon?
I was also trying to update the sidemenu when a user logs in as well, so i tried using: import { Events } from '#ionic/angular';
However I got a warning referring me to this link https://angular.io/guide/observables#basic-usage-and-terms which I failed to follow because am not that familiar with observables.
After much research I found that I can still use events but I had to import them from angular's router directive.
This was my code before:
/* import was */
import { Events } from '#ionic/angular';
import { Storage } from '#ionic/storage';//ignore this import if doesn't apply to your code
/* inside the class */
constructor(
private events: Events,
private storage: Storage
) {
this.events.subscribe("updateMenu", () => {
this.storage.ready().then(() => {
this.storage.get("userLoginInfo").then((userData) => {
if (userData != null) {
console.log("User logged in.");
let user = userData.user;
console.log(user);
}
else {
console.log("No user found.");
let user = {};
}
}).catch((error)=>{
console.log(error);
});
}).catch((error)=>{
console.log(error);
});
});
}
changes i made that actually got my code working and deprecation warning gone:
/* import is now */
import { Router,RouterEvent } from '#angular/router';
import { Storage } from '#ionic/storage';//ignore this import if it does't apply to your code
Rest of code
constructor(
public router: Router,
public storage: Storage
){
this.router.events.subscribe((event: RouterEvent) => {
this.storage.ready().then(() => {
this.storage.get("userLoginInfo").then((userData) => {
if (userData != null) {
/*console.log("User logged in.");*/
let user = userData.user;
/*console.log(this.user);*/
}
else {
/*console.log("No user found.");*/
let user = {};
}
}).catch((error)=>{
console.log(error);
});
}).catch((error)=>{
console.log(error);
});
});
}
I got the idea after seeing this https://meumobi.github.io/ionic/2018/11/13/side-menu-tabs-login-page-ionic4.html. I hope my answer can be useful.
Steps to resolve the issue
import events in login page and in sidemenu view
In login page, after login success do your logic to publish the events.
for eg:
this.authService.doLogin(payload).subscribe((response) => {
if (response.status) {
this.storage.set('IS_LOGGED_IN', true);
this.events.publish('user:login');
}
}, (error) => {
console.log(error);
});
In sidemenu view, create a listener to watch the events 'user:login'
for eg:
this.menus = [];
// subscribe events
this.events.subscribe('user:login', () => {
// DO YOUR LOGIC TO SET THE SIDE MENU
this.setSidemenu();
});
// check whether the user is logged in or not
checkIsUserloggedIn() {
let isLoggedIn = false;
if (this.storage.get('IS_LOGGED_IN') == '' ||
this.storage.get('IS_LOGGED_IN') == null ||
this.storage.get('IS_LOGGED_IN') == undefined) {
isLoggedIn = false;
} else {
isLoggedIn = true;
}
return isLoggedIn;
}
// to set your sidemenus
setSidemenu() {
let isUserLoggedIn = this.checkIsUserloggedIn();
if(isUserLoggedIn) {
this.menus = ['Home', 'Aboutus', 'Contactus', 'My Profile', 'Logout'];
} else {
this.menus = ['Login', 'Home', 'Aboutus', 'Contactus'];
}
}

Ionic3 framework network.onConnect().subscribe not working?

I have created a little phone app with Ionic. I am trying to implement a bit logic where the component knows when its online or offline. To do so I am using the network plugin fom Ionic and it just does not work as expected.
instead of updating the
this.connected
value every time when I switch on / off the network, it will only do so if I switch it off / on AND do something like switching from landscape to portrait mode, or work on a different app for a while and come back to the app.
Really puzzled by that.
Here is the code:
import {Component} from '#angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GooglePlus} from '#ionic-native/google-plus';
import {SurveyService} from "./survey.service";
import {Survey} from "../../Declarations/Survey";
import {SurveyPage} from "../survey/survey";
import {Network} from "#ionic-native/network";
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [SurveyService, Network]
})
export class HomePage {
public surveys: Survey[] = [];
public connected;
public networkType;
constructor(public navCtrl: NavController,
private googlePlus: GooglePlus,
private surveyService: SurveyService,
public navParams: NavParams,
platform: Platform,
private network: Network) {
this.checkForNetwork();
this.surveyService.getAvailable().subscribe(surveys => {
this.checkForNetwork();
this.surveys = surveys;
})
}
login() {
this.googlePlus.login({
'webClientId': '632130231957-dmjd154jhq1eenimedri3m0de6sh7tln.apps.googleusercontent.com'
}).then((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}
logout() {
this.googlePlus.logout().then(() => {
console.log("logged out");
});
}
openSurvey = (survey: Survey) => {
this.navCtrl.push(SurveyPage, {
survey: survey
});
}
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
}
}, 3000);
});
}
}
OK, I worked it out:
Turns out that ionic works perfectly fine, but I tried to change the view of my application depending on whether
this.connected
is true or false. I did not realize that I needed to tell Angular to refresh its view by using Application
applicationRef.tick();
in the right place. So basically, once the Ionic changes the value of this.connected you need to tell Angular about it, here is the corrected part of the code:
You need to inject ApplicationRef into the constructor
constructor(public navCtrl: NavController,
...
private appReference: ApplicationRef) {
...
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
this.appReference.tick();
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
this.appReference.tick();
}
}, 3000);
});
}

Ionic 2: push notification on click

A notification appears, but upon clicking them, they only open the application again. What I want is upon clicking the notification, it opens a specific item.
In Laravel, I am using the brozot/Laravel-FCM package for Firebase Cloud Messaging (FCM) to send notifications, and on the other end, I'm using Ionic push notifications to receive and display notifications in the notification tray.
If I don't use setClickAction() on Laravel, the Ionic application opens upon clicking the notification, but if I set setClickAction(), then nothing happens. The notification merely disappears.
Laravel-code:
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
->setSound('default')
->setClickAction('window.doSomething');
$notification = $notificationBuilder->build();
Ionic 2 framework sample:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav, MenuController, ModalController, Events, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
import { Storage } from '#ionic/storage';
import {
SearchPage
} from '../pages/pages';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = SearchPage;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private menu: MenuController,
private modalCtrl: ModalController,
private events: Events,
private push: Push,
private alertCtrl: AlertController,
private storage: Storage
) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
this.pushSetup();
}
pushSetup() {
const options: PushOptions = {
android: {
senderID: 'xxxxxxxxxxx',
forceShow: true
},
ios: {
senderID: 'xxxxxxxxxxx',
alert: 'true',
badge: true,
sound: 'true'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
});
pushObject.on('registration').subscribe((registration: any) => {
alert(registration.id);
});
pushObject.on('error').subscribe(error => alert('Error with Push plugin' + error));
}
}
(<any>window).doSomething = function () {
alert('doSomething called');
}
What am I missing?
There are these steps that need to be done for general One-Signal push notification to be implemented
Create a OneSignal Account
Add a New APP in the One Signal , configure for Android first (you can target for any platform but i'm focussing on Android as of now) .you need to get the Google Server Key and Google Project Id.
You can get the Above keys from the Firebase using this Steps
Now we are done with Configuring the OneSignal Account, now integrate with the ionic using the cordova plugin
In Ionic2 :
OneSignal.startInit(//google Server Key, //Google ProjectId);
OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
OneSignal.setSubscription(true);
OneSignal.handleNotificationReceived().subscribe(() => {
// handle received here how you wish.
// this.goToReleatedPage(data.Key, data.Value);
});
OneSignal.handleNotificationOpened().subscribe((data: any) => {
//console.log('MyData'+ JSON.stringify(data.additionalData));
this.parseObject(data);
});
OneSignal.endInit();
ParsingObject in Ionic
public parseObject(obj) {
for (var key in obj) {
this.goToReleatedPage(key, obj[key]);
if (obj[key] instanceof Object) {
this.parseObject(obj[key]);
}
}
}
goToReleatedPage Method
public goToReleatedPage(Key, Value) {
//console.log("Pagename"+" " + Key + "ID" +" " + Value);
if (Key === 'xxxx') {
this.navCtrl.push(xxxPage, {
id: Value
});
} else if (Key === 'Foo') {
this.navCtrl.push(foosPage, {
id: Value,
});
} else if (Key === 'bar') {
this.navCtrl.push(barPage, {
id: Value
});
}
}
While sending the Message from OneSignal , you need to specify which page you need to open and you want to pass Id as follows