Android devices has back button on menu toolbar. I want to disable the possibility when i login to my app and click on that back button to route on login page.
I want if user click on back button after login then i close the app.
Here is my initial code for routing below.
if (token) {
this.router.navigate(['/main-tabs/tabs/dashboard'])
} else {
this.router.navigate(['/login']).then();
}
I've tried many other answers but none of them really works for me. But this one works :
To disallow the login from going 'back' to the authenticated page after logged out, just do something like this in your app-routing.module.ts :
{
path: 'home',
loadChildren: './home/home.module#HomePageModule',
canActivate: [LoggedAuthGuard]
}
The same for the opposite (to prevent going back into login page with back button) :
{
path: 'login',
loadChildren: './login/login.module#LoginPageModule',
canActivate: [NotLoggedAuthGuard]
}
And both LoggedAuthGuard and NotLoggedAuthGuard must implement CanActivate. Sample code as below (with Promise, but it also works with boolean return) :
import { Injectable } from '#angular/core';
import {CanActivate} from "#angular/router";
import {Storage} from "#ionic/storage";
#Injectable({
providedIn: 'root'
})
export class LoggedAuthGuard implements CanActivate {
constructor(protected storage: Storage) { }
async canActivate() {
return (await !!this.storage.get('access_token'));
}
}
For the NotLoggedAuthGuard you just returns the opposite of LoggedAuthGuard.
async canActivate() {
return (await !this.storage.get('access_token'));
}
Hope this helps.
This answer provides a solution for removing the login page from the browser's history by replacing it with a page, that the user was navigated to after successful login. It might be a good and quick solution to:
I want to disable the possibility when i login to my app and click on
that back button to route on login page.
What I understood from your question is after user login, You don't want to navigate to login page if back button is clicked. If I understood your question correctly you can try below solution.
one approach is changing root page
this.navCtrl.setRoot(HomePage);
or
You can achieve this by removing page from stack after successful transition. Place below code inside Login success method
let currentIndex = this.navCtrl.getActive().index;
this.navCtrl.push(DestinationPage).then(() => {
this.navCtrl.remove(currentIndex);
});
Hope this helps you.
I think you can do like that :
this.platform.backButton.subscribe((()=>{
if(this.router.url == <insertpathhome>)
{
this.platform.exitApp();
}
else{
//go back
}
});
Related
I have a modal using the modal service:
import { ModalDialogService } from "nativescript-angular/directives/dialogs";
private modal: ModalDialogService,
I can call a modal, for example
this.modal.showModal(MyModalComponent, options).then(res => {
// console.log(res);
});
Now I want to close the modal, but not from within the modal itself. This already works in iOS:
const page = topmost().currentPage;
if (page && page.modal) {
page.modal.closeModal();
} else {
console.log("error closing modal!!!!");
}
But running this with Android, it will always goes to the error console.log, resulting the modal not being closed. The user can still close it (the modal has a close button), but I also want to programaticly close the modal.
That's not the way how you should do it in Angular. Inject ModalDialogParams and use the closeCallback method.
constructor(private modalDialogParams: ModalDialogParams) {}
onCloseButtonTap() {
this.modalDialogParams.closeCallback();
}
I had a similar issue, what I ended up doing was implementing an interface to activate the closeCallback on the modal parameters from the other class. Here is a playground showing what I did https://play.nativescript.org/?template=play-ng&id=q1mDZI&v=6
I am facing a very weird issue with an app which has been working fine and after upgrading to react-navigation v2 has started to have the issue.
Anywhere within the app, the Back Button on Android closes the app and moves it back to the suspended apps.
I have tried many things in terms of handling the back behaviour manually, downgrading some of the packages etc but none of them worked.
Here is my package.json file:
I had the same issue and these are what I found:
https://github.com/react-navigation/react-navigation/issues/4329
and
https://github.com/expo/expo/issues/1786
A temporary solution is mentioned, which is to downgrade firebase to 5.0.3, which works for me.
The issue is with the npm firebase package. There are two ways to fix this.
As mentioned in the other answers, downgrade firebase to 5.0.3
Change the way in which you import firebase. This method will be a lot
easier.
Use:
import firebase from "#firebase/app";
import "firebase/auth";
import "firebase/database";
Don't use import * as firebase from "firebase"; or import firebase from "firebase";
See this GitHub issue for more details.
The solution of downgrading Firebase worked for me too but I had to downgrade to Firebase 4.13.1 as with 5.0.3 I was still facing the issue.
If you are using react-navigation v2, take a look this documentation.
You can also use react-navigation-backhandler for an easy-to-use solution.
Converting this import statement fixed my issue
import Firebase from '#firebase/app' // The issue got fixed after adding #
import 'firebase/auth'
import 'firebase/database'
import 'firebase/storage'
Without the # the backbutton was exiting the user from application
I have faced the same issue, it seems like the implementation of Backhandler.android.js is not correct, you can find the file here node_modules/react-native/Libraries/Utilities/BackHandler.android.js , in this file const subscriptions = Array.from(_backPressSubscriptions.values()).reverse(); piece of code always returns an array of length 0, that's why the invokeDefault variable always stays true and closes the app, you can fix it by handling the back button behavior via your own implementation.
In Navigation Service add this method
import { NavigationActions, StackActions } from 'react-navigation';*
let navigator;
function setTopLevelNavigator(navigatorRef) {
navigator = navigatorRef;
}
function pop() {
navigator.dispatch(StackActions.pop());
}
export default {
pop,
setTopLevelNavigator
};
You need to set the top level navigator in your app.js, like this int render method's return statement
<AppNavigator //Replace it with your navigator
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
onNavigationStateChange={(prevState, currentState) => {
this.setState({ currentState });
}}
/>
To handle the Back button functionality add these things in your app.js
import NavigationService also
import {
BackHandler,
DeviceEventEmitter
} from 'react-native';
In componentDidMount add these
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleHardwareBack);
}
In componentWillUnmount add these
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress',this.handleHardwareBack);
}
Now handling the hardware back button
handleHardwareBack = () => {
if (!isUndefined(this.state.currentState)) {
const mainRouteIndex = this.state.currentState.index;
const mainRoute = this.state.currentState.routes[mainRouteIndex];
const subRouteIndex = mainRoute.index;
if (subRouteIndex === 0) {
console.log(
'the screen name is ----> ',
mainRoute.routes[subRouteIndex].routeName
);
this.toggleExitModal(); //you can place any dialog if you want to show
return true;
}
NavigationService.pop();
return true;
}
console.log('Back Button is handled in the respective page seperately');
};
return true tell that we are going to handle the back button functionality manually, return false will lead to exits the app as by default it is Hardware back button closes the app :(
Hope this will help you
Well i am using firebase 5.5.5 i don't have any problem with navigation , I think you need to create your stack navigator to use the back butoon properly , I have given a example of it. pages are imported also i have not attached the screen importing code
import { createSwitchNavigator, createStackNavigator } from 'react-navigation';
const Drawer = createDrawerNavigator(
{
BrowseQuestion: BrowseQuestion,
BrowseCategory: BrowseCategory,
}
);
const Loginstack = createStackNavigator({
Login: LoginScreen,
Forgot: ForgotPassword,
Signup: SignupScreen,
})
export default createSwitchNavigator({
Login : Loginstack,
Account: Drawer,
},
{
initialRouteName: 'Login'
}
);
I try to disable back button on android device with "keyboard: false" but it not work.
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope,
keyboard: false
})
How to disable it.
Thank you.
ionicModal provides hardwareBackButtonClose option to set false for this behaviour.
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope,
hardwareBackButtonClose: false
})
Please see related documentation : http://ionicframework.com/docs/api/controller/ionicModal/
Another option could be: isShown() method as mentioned in the docs http://ionicframework.com/docs/api/controller/ionicModal/
You can go for something like this
if(!$scope.modal.isShown()){
navigator.app.exitApp();
} else{
//do nothing...
}
Check this thread: Disable hardware back button in Ionic application?
This should do it:
$ionicPlatform.registerBackButtonAction(function () {
if (condition) {
navigator.app.exitApp();
} else {
handle back action!
}
}, 100);
But I would advice against this unless you really need to. Breaking the expected model of operation very slightly hurts the entire platform.
Im stuck in a problem that i have to open a specific page in ionic framework using the controller.
I have to go to the following page
#/tab/hotel_details/1
when i click ok button in the ionic popup window
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Click OK for further details',
});
alertPopup.then(function(res) {
//Go to a specific page
});
};
I cant use $state.go("tab.hotel_details"); , because i have to go to hotel_details/1
I have to get rid of the above problem for further development of my app.
You can pass the id in the second parameter of the call to $state.go :
$state.go("tab.hotel_details", { "id": id })
Then, in your controller, you can retrieve the value from $stateParams :
var id = Number($stateParams.id)
Reference: Angular-ui State
You can still use the $location service if you want to navigate to a particular url instead of navigating by a state.
$location.path('/tab/hotel_details/1');
I would like to disable or override the Android Back button while I am navigating pages on the InAppBrowser. Can I add an event listener that can handle that?
EDIT:
Looking at the answer by #T_D below the solutions provided are the closest I could get to. It does not seem to be possible to override the button in InAppBrowser as all the PhoneGap tweaks stop working while navigating pages on this plugin. I was not able to find any other solution rather than modifying the API library. If there are any PhoneGap guys here and know something more, I 'll be glad to get some comment. Thanks.
The closest I got:
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener("backbutton", function () { })
According to the documentation the behaviour of the hardware back button can be configured now for the InAppBrowser:
hardwareback: set to yes to use the hardware back button to navigate backwards through the InAppBrowser's history. If there is no previous page, the InAppBrowser will close. The default value is yes, so you must set it to no if you want the back button to simply close the InAppBrowser.
Thanks to Kris Erickson.
So just update your InAppBrowser plugin if the backward navigation is the desired behaviour.
For more details see: https://github.com/apache/cordova-plugin-inappbrowser/pull/86
You can do it quite easily now (as of InAppBrowser version 0.3.3), but you will have to edit the Java files. Go to src/com/org/apache/corodova/inappbrowser directory and edit the InAppBrowserDialog.java:
Change
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
// better to go through the in inAppBrowser
// because it does a clean up
this.inAppBrowser.closeDialog();
}
}
to
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
if (this.inAppBrowser.canGoBack()) {
this.inAppBrowser.goBack();
} else {
this.inAppBrowser.closeDialog();
}
}
}
Then go to InAppBrowser and find the goBack function, change:
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
to
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
And now the hardware back button will go back until there are no more backs to do. I really think this should be the default behavior in android since the Done button already closes the InAppBrowser window.
This worked for me in PhoneGap 2.7, help came from here, How do I disable Android Back button on one page and change to exit button on every other page
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.addEventListener("backbutton", function (e) {
e.preventDefault();
}, false );
}
I was having this same issue and finally got it to work, I'll post the answer here in case it helps someone.
This is the code I use:
window.new_window = window.open(url, '_blank', 'location=no');
window.new_window.addEventListener("exit", function () {
window.new_window.close();
});
So the key basically is to attach the exit event, which gets called when the back button of the device is tapped.
BTW, I used cordova.js, and build my apps locally using the Cordova CLI, I don't know if that makes any difference, I mention it just in case.
EDIT NOTE: As far as I know, it's not possible to override the back-button for the InAppBrowser in PhoneGap. But I did my best searching for possible solutions...
There's an eventListener to override back-button in PhoneGap -doesn't work for InAppBrowser-
function onDeviceReady(){
document.addEventListener("backbutton", onBackKeyDown, false);
}
Alternative eventListener to override back-button -the OP said this didn't work either-
var ref = window.open('http://www.stackoverflow.com', '_blank', 'location=yes');
ref.addEventListener("backbutton", function () {
//logic here
})
Overriding the Back-button in an Activity -this is plain java, obviously didn't work in PhoneGap-
#Override
public void onBackPressed()
{
//logic here
}
Conclusion:
Above solutions didn't work, following links (this answer, this one and a third one) didn't help either. So it's highly possible that overriding the back-button for the InAppBrowser in PhoneGap is not possible. If someone does come up with a solution or if things changed for a new PhoneGap version feel free to let us know...
EDIT:
Installing this plugin may take you to closest solution:
cordova plugin add org.apache.cordova.inappbrowse
What this plugin will do, in WP8, it will overlay back/forward/close button on InAppBrowser whenever you open any link/page in it.
See this image:
Use jQuery mobile:
$(document).on('backbutton',
function(e){
e.preventDefault();
// YOUR CODE GOES HERE
});
Running Cordova 5.1.1 and when i load pages in the inappbroswer i like having the back button work until the inappbrowser exits back to my index.html page because it's blank and just sits there. So i used the following code to fix this. It exits the app when it exits the inappbrowser.
window.open = cordova.InAppBrowser.open;
var ref = window.open(url, '_blank', 'location=no');
ref.addEventListener('exit', function () {
navigator.app.exitApp();
});
As far as I know it's not possible to override or detect the back button from inAppBrowser. When you press the back button, inAppBrowser will hide and return control to the Phonegap page. You can catch this with the focus event on the window, (using jQuery) like
var browser = window.open('http://example.com', '_blank', 'location=no');
$(window).on('focus', function() {
browser.show();
});
to reopen the browser. You could then use browser.executeScript() to signal the webapp loaded in the browser, if you like.
Inspired by this forum post.
I know this question has an answer already but I post my answer for those who any of these answers didn't work for them(such as myself):
so I have a multi page app for android and IOS and I am using cordova 5.x and I added the code below in every page except the page I needed InAppBrowser:
delete window.open;
and then for the rest of the pages I used:
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(event) {
// your code for handling back button comes here
}
for handling back button
note that: delete window.open; base on the documentation
manually restore the default behaviour of 'window.open'
after that InAppBrowser plugin worked great and I handled back button in all pages correctly.
one last thing don't forget to add:<script type="text/javascript" charset="utf-8" src="cordova.js"></script> in pages you need to have InAppBrowser.
hope this help.