Repeatedly triggering navigator.notification.confirm() function

I am currently working on a JSON loop that retries connection 3 times before triggering an error. However, I have encountered a situation where multiple JSON requests are made, resulting in several alerts being displayed in my phonegap app.

For example:

function showJSONerror(xhr, status)  {
    
    if (xhr.status === 0 && localStorage["TmpAlertShow"] !== true) {
        navigator.notification.confirm('Connection error.\n Verify your network connection and try again.', confirmAction, 'Woops...','Try Again, Close');
        localStorage["TmpAlertShow"] = true;

        function confirmAction(button) {
            if (button == 1) { 
                localStorage["TmpAlertShow"] = false; 
                showPage(localStorage["TmpWebView"]);
            }  
            if (button == 2) { 
                localStorage["TmpAlertShow"] = false; 
                return false; 
            } 
        }
    }
}

I am looking for a solution to either close previous alerts using JavaScript or keep track of whether an alert has already been triggered and not closed to prevent displaying multiple alerts.

Thank you

Answer №1

If you're looking for a solution, one approach could be to set up a global variable that keeps track of the number of requests currently in progress. Then, in your error handling function, you can check if there are any requests running. If there are, you can store the results in a global array; if not, you can proceed with processing the errors for display.

Here's an example:

var requestsRunning = 0;
var requestResults = [];

Each time a call is initiated, increment the count:

requestsRunning++;

Once a call is completed, decrement the count:

requestsRunning--;

In your error handling function:

if(requestsRunning > 0) {
    requestResults.push(/*whatever data you want to collect*/);
}
else {
    /*compile results for error display*/
}

Answer №2

I've encountered a comparable issue in the past

My solution involved visiting http://underscorejs.org/#after

Perhaps you could try this approach as well?

Answer №3

Although this issue may be considered old, it continues to persist on Android even with Cordova 12.x in December 2023. To tackle this problem, I implemented a workaround by introducing a one-second delay boolean. While I believe there might be a more elegant solution available, this current approach has proven effective thus far.

// Implementing a boolean to avoid accidental/multiple doConfirm calls (known Android quirk?)
var doConfirmJustRan = false;

function doConfirm(confirmText, confirmTitle, confirmCallback){

  try{
    /* Check if doConfirm was just executed - prevent redundant calls */
    if(doConfirmJustRan == true){
      console.log('doConfirm() attempted to execute again/too soon [' + confirmText + ']. Exiting now.');
      return;
    } 

    /* Execute main navigator.notification.confirm functionality here ... */

    /* Reset variable after 1 second (?) */  
    doConfirmJustRan = true;
    window.setTimeout(function(){doConfirmJustRan = false;},1000);
    
  }catch(e){ /* Handle errors */ }
}

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

ES6 syntax does not allow for exporting routers

Looking to convert NodeJS modules (constant xxx = require('yyy')) into ES6 format, but encountering errors when exporting the router using the export syntax in ES6: throw new TypeError('Router.use() requires a middleware function but ...

Load MP3 or MP4 files upon initial loading

I am trying to automatically play an MP3 audio file as soon as my page loads, ideally using JavaScript. The audio should only play once and at the beginning Despite referencing W3Schools and Mozilla documentation on the audio element, I couldn't get ...

When the submit button on the contact form that utilizes jquery, ajax, and mailer php script is clicked, no action

I've set up a contact form on my website and I'm attempting to enable email functionality so that when users input their information and hit submit, it gets emailed to me. I'm using jQuery, AJAX, and a PHP mailer script that I found in this ...

How can I enable the feature of automatic address population when entering a PIN CODE in an Angular application?

I have created an HTML file where I aim to automatically fill in the DISTRICT, STATE, and CITY fields once a user enters the PIN CODE. The data will be fetched using an API. The API link is: <div class="cardParts5"> <di ...

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

Auto-collapse sidebar upon clicking anywhere on the page

I have a dynamic sidebar that appears when the user clicks on a hamburger button. Here is the layout: $('#nav-toggle').click(function() { if($('#nav-toggle').hasClass('active')){ $('.menu').animate({ r ...

Retrieving Individual Data from JSON URL for Dashing Dashboard

I'm attempting to display the "sgv" value on a Dashing / Smashing dashboard widget. I'd also like to show the "direction" value eventually. However, I'm encountering difficulties in extracting that specific value, which changes every 3 to 5 ...

What is the best way to simultaneously update multiple objects within an array in mongoDB?

Is there a way to efficiently update multiple objects in an array within MongoDB? Let's say I receive an array of titles from the client that need to be modified. For example: Data received from the client: [0,3] Document stored in MongoDB: [ { ...

Is it possible to intercept Angular core methods in order to implement some Aspect-Oriented Programming strategies?

Currently working on a project using Angular 12, I'm wondering if there's a way to intercept calls to core methods like createComponent() from ViewContainerRef in the @angular/core library. This would allow me to implement some aspect-oriented pr ...

Mobile site experiencing owl.carousel responsiveness issues after refreshing the page

I am currently working on a website located at . On the homepage, right after the slider, there is a carousel of three info boxes. However, in mobile view (developer mode), after a hard refresh or viewing the link on an actual mobile device, it displays a ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

What is the purpose of assigning controller variables to "this" in AngularJS?

Currently, I am analyzing an example in CodeSchool's "Staying Sharp with Angular" course in section 1.5. Here is the code snippet: angular.module('NoteWrangler') .controller('NotesIndexController', function($http) { var contro ...

Utilizing an Object as a key within another Object

Can we actually use an object as a key inside another object? After some investigation, it appears that the answer is NO, but the explanation is not very clear. Here is an example: let user1 = { name: "John Doe" }; let numberOfAnswers = {}; // ...

How to Retrieve URL Parameters in Gatsby

As I delve into learning React and Gatsby, I encountered an issue with my page containing URL parameters. Despite everything working smoothly on my local machine, after the gatsby build process, the variable url = undefined. How can I retrieve these para ...

Issue with multiple dropdown menus not closing when clicked on

The current implementation provides the functionality to convert select boxes into list items for styling purposes. However, a drawback of the current setup is that once a dropdown is opened, it can only be closed by clicking on the document or another dr ...

Access to JSON.stringify is prohibited

I have an array containing objects in JavaScript that I need to save as a .json file. Prior to saving the objects, I displayed them using console.log. // Client Object {id: "1", color: "#00FF00"} Object {id: "2", color: "#FF7645"} Object {id: "3", color: ...

Guide on how to retrieve a value using image.onload on the client side

I have encountered an issue with exporting a png image from an svg element using Blob. The problem arises when clicking the anchor tag to export the image, as the content is not rendered due to the asynchronous method (image.onload()) being called after th ...

The ReactJS application is experiencing issues when run on an outdated version of Chrome, specifically version

I recently set up a new ReactJS project using create-react-app, with node Version 12.22.12. To ensure compatibility with older browsers, I incorporated the polyfill core-js. As a result, the project now functions smoothly on Chrome versions 31 and above; h ...

How can the loader method be triggered from within a React component?

Utilizing a loader from react-router-dom to retrieve data for the component. Additionally, there is another function embedded within the component that updates certain information obtained through the loader. I am seeking a method to retrigger the loader ...

Sending state data in an Axios POST request

I'm trying to include a state in an axios post request to send data to my backend, but I'm getting an error saying the state I selected is not defined. Here's the code snippet: React frontend import React, { Component } from "react&qu ...