When registering the onHardwareBackButton event in Ionic, the back button continues to successfully navigate to the previous page

I recently started working with Ionic and encountered an issue with the onHardwareBackButton event. The event is functioning properly and directing me to the register function, but even after going to the register function, it still navigates back to the previous page. I have a Cordova confirm dialog box set up in the hardwarebackbutton event function so that when the user clicks cancel, they can navigate back to the previous page. However, now the popup appears simultaneously with the navigation back. I have tried various solutions like using:

e.preventDefault()

e.stopPropagation() 

but unfortunately, neither of them worked for me. I also attempted to use the registerBackButtonAction event, but it doesn't deregister when I leave the page. I have been stuck on this issue for hours. Below is the code snippet I am currently using:

// Registering the event

showAlertPopup = function(){
// Show the popup
}

$scope.$on '$ionicView.enter', (event, view)->
    $ionicPlatform.registerBackButtonAction showalertPopup, 100

// Deregistering the event

$scope.$on '$ionicView.leave', (event, view)->
    $ionicPlatform.offHardwareBackButton showalertPopup

Instead of registerBackButtonAction, I have tried using onHardwareBackButton.

Answer №1

To implement this functionality, you can use the registerBackButtonAction method with a priority of 100. The priorities for different back button actions are as follows:
Return to previous view = 100
Close side menu = 150
Dismiss modal = 200
Close action sheet = 300
Dismiss popup = 400
Dismiss loading overlay = 500

By setting the priority to 100, you will be overriding the default "Return to previous view" action. Remember to handle the de-registration when leaving the view:

var backbuttonRegistration = null;

$scope.$on('$ionicView.enter', function(event, viewData) {
    backbuttonRegistration = $ionicPlatform.registerBackButtonAction(function(e) {
            e.preventDefault();
            showalertPopup();
        }, 100);
});

$scope.$on('$ionicView.leave', function(event, viewData) {
    if (backbuttonRegistration)
    {
        backbuttonRegistration();
    }
});

The registerBackButtonAction method returns a function that can deregister the specific backButtonAction.

Your controller function should follow this pattern:

.controller('homeController', function($scope, $ionicPopup, $ionicPlatform) {

    function showalertPopup() {
      var alertPopup = $ionicPopup.alert({
        title: 'Don\'t eat that!',
        template: 'It might taste good'
      });
      alertPopup.then(function(res) {
        console.log('Thank you for not eating my delicious ice cream cone');
      });
    }

    var backbuttonRegistration = null;

    $scope.$on('$ionicView.enter', function(event, viewData) {
        backbuttonRegistration = $ionicPlatform.registerBackButtonAction(function(e) {
                e.preventDefault();
                showalertPopup();
            }, 100);
    });

    $scope.$on('$ionicView.leave', function(event, viewData) {
        if (backbuttonRegistration)
        {
            backbuttonRegistration();
        }
    });

});

Note: You can also set the priority of registerBackButtonAction to the highest value like 1000 for even more control over the back button behavior:

    backbuttonRegistration = $ionicPlatform.registerBackButtonAction(function(e) {
            e.preventDefault();
            showalertPopup();
        }, 1000);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

"Troubleshooting Bootstrap nav-pills' failure to update displayed content

I'm currently working on creating a dynamic navbar that updates the content based on which navigation pill is selected. For some reason, the content in my div.tab-content isn't changing as expected... Here is an example of the code I am using: ...

Having trouble accessing a DOM element within a Vue component while using vanilla JavaScript

I am attempting to dynamically update data from a Vue component using jQuery in a Webpack project. Below is the code snippet: <template> <div id="container"> <slot>show string!!</slot> <div id="s_container"&g ...

There seems to be an issue with the Link component from react-router-dom when used in conjunction with

I am currently utilizing react-router-dom along with Material-ui My main objective is to create a clickable row in a table that will lead to a specific path. Here is the code snippet: .map(client => ( <TableRow key={client.id} component={Link} to ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

The React JSON Unhandled Rejection problem requires immediate attention

While working on a form in React 16, I reached out to a tutor for some guidance. However, when trying to mock the componentDidMount, I encountered an error that has left me puzzled. The app still runs fine, but I am curious as to why this error is occurrin ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Ways to implement standard sorting in react-table

Currently, I am utilizing react-table v7 to generate tables. You can find more information about react-table at https://www.npmjs.com/package/react-table. While working with the table, I was able to implement sorting for all columns by following this e ...

Looking for some specific instances of binding attributes within custom AngularJS elements?

I am in the process of developing a custom tag that resembles the following: <mytag type="Big" /> where "type" is an attribute that will be linked to the component and set the text in a label, like so: <label>{{type}}</label> ... (oth ...

Ajax Form Submission

My query relates to a combobox I have integrated: <select id='addOPTION' onchange='fillADDid(this.value);'> <option value=0>Select</option> <option value=1>etc</option> <option value=2>etc</option ...

How to align scrolling images with their scroll origin - a step by step guide

Curious to know the name of the effect where images scroll in a different orientation than the page, creating a 2D appearance. Take a look at the Google Nexus website and scroll down - do you see the effect? What is this effect called? Is it created usin ...

Modify the selected option in a dropdown using an Angular controller

I am trying to update the "selected value" of a dropdown to match the value that is already saved in the database. Is there a way to achieve this? Controller var app = angular.module('app', []); app.controller('ctrl', function($scope ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

Issue: The initiation function fails to start data

I have created an app using Ionic framework that displays articles. When a single article is opened, I use the init function in the UserService to initialize user data: angular.module('coop.services') .factory('UserService', function( ...

Concealed checkbox value in jQuery

I have a problem with setting the hidden checkbox "marketingPhone" to TRUE when the "marketingAAA" checkbox is checked as true. This part works fine. However, if any other checkbox on the page is set to TRUE, then it also sets "marketingPhone" to TRUE. I ...

Expand the capabilities of a jQuery plugin by incorporating new functions or modifying existing ones

I have a task to enhance the functionality of a jQuery Plugin (https://github.com/idiot/unslider) by adding another public method. (function(){ // Store a reference to the original remove method. var originalMethod = $.fn.unslider; // Define a ...

Unusual behavior exhibited by angular bootstrap collapse

I've encountered some unusual behavior with uib-collapse. Imagine I have a list of elements that I want to collapse individually. Additionally, I want to periodically refresh the content based on certain criteria. For instance: I have various items, ...

"Use Highcharts to visually compare the data from one month in two different years

How can I use Highcharts Columns to compare data from two different years within the same month? Check out the example image below: https://i.sstatic.net/8MMsA.png The data structure is as follows: myData[0] = { data1:"0.00", data2:"0.00", data3:"868.0 ...

Unable to utilize the "fs" module within a Three.js application

After utilizing this base code to create an app with Three.js, I attempted to incorporate node's fs module for filesystem interaction. Despite adding const fs = require("fs") in my app.js file, the module could not be located. The error mess ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...