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.
Related
I'm developing an app with Angular 7 and Cordova 8. I want to override the cordova back button event, to prevent the app from closing by adding an event listener as described in the cordova docs
My code looks like this:
let onDeviceReady = () => {
enter code hereconsole.log("Bootstraping Module...")
document.addEventListener("backbutton", (e) => {e.preventDefault(); e.stopPropagation(); console.log("backbutton"); return false;}, false);
platformBrowserDynamic().bootstrapModule(AppModule);
};
document.addEventListener('deviceready', onDeviceReady, false);
According to the docs this should prevent the app from closing. I know that the preventDefault, stopPropagation and return false calls are not necessary, but I found the as possible solutions to my problem, which all didn't work.
When I press the back button, I see the backbutton print, however, the app is still closing.
Tested on Android.
Update: After debugging the issue using logcat I could see the message WARNING: Back Button Default Behavior will be overridden. The backbutton event will be fired! which is logged in the CoreAndroid plugin class when the back button is overriden in the native Android app. Still when I press the button, the app exits
Update: The issue was related to OnsenUI, see my answer below
We handed the backbutton logic in app.component.ts ngOnInit
import {Renderer2} from '#angular/core';
constructor(private renderer: Renderer2){}
ngOnInit(){
const devicebackbutton = this.renderer.listen('document', 'backbutton', e => {
e.preventDefault();
e.stopPropagation();
return false;
});
}
I managed to solve the issue. It wasn't caused by Cordova or Angular, but by OnsenUI, which I used for input components.
By default it overwrites all cordova handlers for the backbutton, as it provides its own functionality. You can read more here
I'm trying to control how the android hardware back button behaves in my app. I had it all working but now I can't reproduce it. The code I'm using is in app.js. I'm expecting the back button to do nothing but write to the console.
.run(function($ionicPlatform) {
$ionicPlatform.onHardwareBackButton(function() {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!")
});
Can any one see what the problem is? I'm running ionic CLI v1.7.11. I'm running the code with ionic view on android
You can find full details, including a full working solution for both hard & soft back buttons at my related post:
Ionic override all BACK button behaviour for specific controller
To summarise how I handled the hardware back button, the trick is to register an action for the Back button, using code like this:
var doCustomBack= function() {
// do something interesting here
};
// registerBackButtonAction() returns a function which can be used to deregister it
var deregisterHardBack= $ionicPlatform.registerBackButtonAction(
doCustomBack, 101
);
$scope.$on('$destroy', function() {
deregisterHardBack();
});
The actual setting is done in that second block calling $ionicPlatform.registerBackButtonAction().
This returns a method that can be called to deregister the action later on if you want to.
It was a ionic view problem. Seems it does not support this.
I have the following logic for my mobile app using cordova and angular.js
Process my logic in mobile.js included in index.html like saving the files on sdcard then redirect the user to the second html page using
window.location.href="main.html";
which will use the files put in sdcard by mobile.js
The issue I'm facing is that when I am on the homepage on main.html and the user presses the back button it comes back to the index.html file and then, after processing goes back to main.html instead of App closing.
I tried using the history.length object with the "backbutton" eventListener
document.addEventListener('deviceready',function(){
document.addEventListener('backbutton',function(e){
console.log("history is "+history.length);
if(history.length==1){
e.preventDefault();
navigator.app.exitApp();
}
else{
navigator.app.backHistory();
}
},false);
},false);
but it doesn't decrease the length when going back, only increases it, so the app goes back to index.html.(history.length is always greater than 1)
I have looked the solution available, like
document.addEventListener("backbutton", function(e){
if($.mobile.activePage.is('#homepage')){
/*
Event preventDefault/stopPropagation not required as adding backbutton
listener itself override the default behaviour. Refer below PhoneGap link.
*/
//e.preventDefault();
navigator.app.exitApp();
}
else {
navigator.app.backHistory()
}
}, false);
but the issue in using it is, if the user goes to
second-page->homepage->third-page->homepage
the app will exit, but instead should go to the third-page.
You could use the jQuery mobile pageload event to keep your own history list, whose length does decrease when you go back. Something like this (untested off the top of my head, so might not be exactly correct):
var pageHistory = [];
$(document).on("deviceready", onDeviceReady);
function onDeviceReady(){
$(document).on("pagecontainerload", onPageLoad);
$(document).on("backbutton", onBackButton);
}
function onBackButton(e){
e.preventDefault();
pageHistory.pop();
if(pageHistory.length==0){
navigator.app.exitApp();
}
else{
navigator.app.backHistory();
}
}
function onPageLoad(e, ui){
var pageId = ui.toPage.attr('id');
if(pageId !== pageHistory[pageHistory.length]){
pageHistory.push(pageId);
}
}
This question already has an answer here:
How to disable the default JQM page in a SPA?
(1 answer)
Closed 8 years ago.
I've seen a couple of posts on this topic but none of them offered a suitable solution.
Once a user navigates to the next page I want to prevent him from going back to the previous ones. I have no back buttons in my pages but back navigation is still possible by tablet/phone device back button.
I believe it's something with preventDefault and stopImmediatePropagation but I don't know how to target the device/browser back button.
I found a good way of doing this, tested it with android and it's working fine.
First of all, make sure you have cordova.js added to your library.
Second, add the following just above the closing header tag, inside:
<script>
function onLoad() {
document.addEventListener('deviceready', deviceReady, false);
}
function deviceReady() {
document.addEventListener('backbutton', backButtonCallback, false);
}
function backButtonCallback() {
navigator.notification.confirm('do you want to exit the app?',confirmCallback);
}
function confirmCallback(buttonIndex) {
if(buttonIndex == 1) {
navigator.app.exitApp();
return true;
}
else {
return false;
}
}
</script>
Third and final, change your starting body tag with:
<body onload="onLoad()">
In my Phonegap app, created in a single html file using div as pages, I override the Back button to exit the app, only if the div that acts as the Home page is visible, otherwise to hide the others and show the home div. I use jQuery to attach the event handlers.
It works well at first app launch, but if the app is in the History list, the override is not working, the Back button exits the app without checking which div is visible. After deleting the app from the History list it works as expected again.
Tested on Nexus 4 with Android 4.2.
Here is the code:
$(document).on('backbutton', function (ev) {
ev.preventDefault();
if (!$('#divHomeScreen').is(':visible')) {
$('.screen').hide();
$('#divHomeScreen').show();
return false;
} else {
navigator.app.exitApp();
}
});
Thanks for your help.
What I have done is dynamically add and remove the backbutton handler as needed. For example...
function showScreen()
{
$("#divHomeScreen").hide();
$(".screen").show();
$(document).on("backbutton", onBackButton);
}
function hideScreen()
{
$(".screen").hide();
$("#divHomeScreen").show();
$(document).off("backbutton", onBackButton);
}
function onBackButton()
{
hideScreen();
}
This was tested on Galaxy S3 Android 4.3 and PhoneGap 3.3.0