Could a personalized "exit page" confirmation be created?

I am looking for a solution that will allow me to pause the execution of my code, display a dialog box, and then resume execution only after a specific button is pressed.

For example, if a user navigates from one page to another on my website, I want a dialog box to appear. If the user confirms the action by clicking a button in the dialog box, then the navigation should continue.

I am aware of the $routeChangeStart event, which provides information about the next route, but it seems to only handle preventing the route change. I am interested in finding a way to delay the route change and trigger it later.

My ideal approach would involve using event.preventDefault() within $routeChangeStart, storing the details of the next route, and then triggering the route change confirmation through user interaction.

Does anyone know how I could reapply a route change? One potential method could involve manipulating the originalPath using the params object and $location, but I am curious if there is a more direct way to achieve this.

Answer №1

It is necessary to utilize string-parsing in this scenario.

If you prefer to handle the confirmation asynchronously, the recommended approach is to prevent the event by default, prompt the user for confirmation, and if granted, set a flag before using $location.url(...) to navigate to the desired page.

app.controller('myCtrl', function ($location, $scope, UserConfirm) {
    $scope.$on('$locationChangeStart', function (evt, next, prev) {
        if (!$scope.exitConfirmed) {
            evt.preventDefault();
            var url = extractUrl(prev, next);
            UserConfirm.confirm('Are you sure you want to leave ?').then(
                function (confirmed) {
                    if (confirmed) {
                        $scope.exitConfirmed = true;
                        $location.url(url);
                    }
                }
            );
        }
    });
    ...
});

The extractUrl() function could be implemented as follows:

function extractUrl(prevAbsUrl, nextAbsUrl) {
    var idx = prevAbsUrl.length - $location.url().length;
    var withNumSign = nextAbsUrl.substring(idx);
    var pureUrl = withNumSign.substring(withNumSign.indexOf('/'));
    return pureUrl;
}

Take a look at this brief demonstration.

Answer №2

Using the $locationChangeStart event, you can access the complete URLs of both your current and future destinations without the need for parsing.

My approach to handling this was as follows:

function confirmLeaving(evt, next, current) {
  if(consideringClosing)  //allow leaving
    return;

  evt.preventDefault();  //Display dialog instead of leaving.

  $('#dialogCancel').modal('show');
  consideringClosing = true;  //It's okay to leave if user tries again after opening dialog.
}   

$scope.$on('$locationChangeStart', confirmLeaving);

Within the modal, there is a "close without saving" button that triggers a $location back to the item list. Since consideringClosing is now true, the confirmLeaving function won't prevent the action. Additionally, the modal contains a cancel button that closes it and resets consideringClosing to false (ensuring the modal will reappear on location change).

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

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

Tips for personalizing the color scheme of Material UI Stepper Step?

I need help customizing the disabled Step color for Material UI Steppers. The default colors are Blue for enabled steps and Grey for disabled steps, but I want to change it to a different color as shown in this example: https://i.stack.imgur.com/HGGxp.png ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

What sets asyncData apart from methods in Nuxt.js?

I am currently utilizing asyncData to fetch data from an API, however it is restricted to pages and cannot be used in components. On the other hand, methods can be used in both pages and components. As these two methods function similarly, I am consider ...

What is the process for importing a class (.js file) into a .vue file?

I am facing an issue with my Vue application. I have created a class named `Authenticator` in the file `Authenticator.js`, and now I need to utilize its functions in my `Login.vue` file. Could someone guide me on how to properly export the `Authenticator` ...

Steps to alter background image and adjust its height upon function activation

I am working on a search page with an advanced search option that only certain users can access. I need the height of my div to increase accordingly and also change the background image to a larger size when the advanced search is selected. How can I make ...

The dimensions of the pop-up window in Chrome's JavaScript are not displaying correctly

My goal is to launch a new chat room window on our website. The dimensions of the chat room are set to 750px x 590px. Below is the link I am using to trigger the javascript popup. <a href="javascript:void(0)" onclick="window.open('http://gamersuni ...

Mastering Angular Protractor for End-to-End Testing

Currently working on an end-to-end test for my Angular application using Protractor. While I can mock httpBackend for unit tests, I prefer to make actual server calls and test against the JSON response. Despite researching on stackoverflow, I'm still ...

Issue with database connection on iOS device seems to be causing trouble

Working on an Ionic Phonegap project for iOS has been a challenge. One specific method in Appdelegate.m caught my attention as it makes an AJAX request to fetch a text file from a server, containing a crucial URL necessary for the app's functionality. ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Mongoose is unable to update arrays, so it will simply create a new array

Having trouble updating my collection without any errors. Can someone lend a hand? I've been at this for 3 hours now. const product_id = req.body.cartItems.product_id; const item = cart.cartItems.find(c => c.product_id == product_id); i ...

What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this: array = [ { name: "john", tag: ["tag1", "tag2"] }, { name: "doe", tag: ["tag2"] }, { name: "jane", tag: ["tag2", "tag3"] } ]; My goal is to create a new array of objects that only contain elements with ...

The jQuery countdown plugin is yielding some unexpected outcomes

Feeling a bit rushed for time, so I thought I'd ask here. The date is currently 2012-10-06 and I'm attempting to implement a jQuery plugin called "jquery.countdown.js". It seems pretty straightforward. Can anyone point out what I might be doing i ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...