Prevent User from Leaving Until Postback Occurs (Implementing in Javascript/ASP.NET)

I have a few functions that run during postback, and they can sometimes take a bit of time to finish.

When a postback is triggered, I display a loading image using the following code:

function showLoader()
{
    document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
}

Now, I want to enhance this function so that if a user tries to leave while it's still running, they are notified that the operation is incomplete.

I came across this code snippet:

function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'Are you sure you want to leave?'; //This message is displayed on the dialog box
    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye;

This solution works, but I only want the code to be active when the loading image is visible.

I attempted the following modification, but it prompts the alert message when the page finishes postback:

function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'Are you sure you want to leave?'; //This message is displayed on the dialog box
    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
function showLoader()
{
    document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
    window.onbeforeunload=goodbye;
}

Do you have any suggestions on how I can modify this to only prompt the user when they try to leave the page, not when the postback process completes?

Answer №1

In order to ensure that the window.onbeforeunload is set to null upon form submission, you should include the following code:

<form onsubmit="window.onbeforeunload=null">

To streamline this process for all forms dynamically, it would be advisable to create a window.onload function that automatically handles this task without requiring individual modifications to each form across your website.

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

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

Executing a closure within a promise's callback

Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution. After reading Mozilla's documentation on closures in loops, I decided to create inner closures. When ...

Tips for displaying dynamic content in VueJS?

I'm currently working on an app that allows users to choose which type of vuetify element they want to display on the page. There are 4 options available for selection. My goal is to render the corresponding vuetify component when a user clicks on the ...

Tips for preventing the error: Combining spaces and tabs?

Every time I use my Vue.js app, this pesky 'error' message keeps popping up. Annoying Error: Mixed spaces and tabs (no-mixed-spaces-and-tabs) at location src/components/Landing.vue line 388: I'm curious about how to get rid of this annoyi ...

Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with ...

Executing an SSRS .rss script file in IIS/ASP.NET: A step-by-step guide

How can I run a .rss SSRS script file within an ASP.NET application on IIS 7.x? Is it necessary to adjust the privileges of the IIS AppPool running my web app in order to run the rs.exe console application with the .rss script? Or is there an alternative ...

The error message in AuthenticatedLayout.jsx on line 43 indicates a problem with trying to access properties of an undefined object, specifically the 'name'

I am encountering this issue react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'name') at AuthenticatedLayout (AuthenticatedLayout.jsx:39:55) AuthenticatedLayout.jsx import { useState } from "re ...

The constructor THREE.Geometry does not exist in this context

I have been working on a three.js open world game and I am trying to implement a rain effect. I have followed tutorials and looked through source code on various github repositories, but I still can't figure out what I am missing. Currently, I am usi ...

Focus on input using jQuery (fixed focus)

How can I ensure that my input always has value and the focus remains fixed on it until values are typed, preventing the cursor from escaping the input field? While I know the existence of the focus() function, how can I effectively utilize it as an event ...

What could be causing the error 'i is not defined' in my Vue.js component script when using a basic for loop?

I have a task where I need to sort an array by version and then move all elements starting with 'ipad' to the end of the list. This code snippet is extracted from a single file Vue.js component: computed: { orderedUsers: function () { ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

What is the method for setting a condition within the setState function?

I used if for the title: in SetConfirmDialog, but it's not working. How can I fix this? <Button color={user.active ? "success" : "error"} variant="text" startIcon={<UserCheck />} title={user.active ? &quo ...

Fade away effect for the session flash message

How can I implement a flash message session for Laravel? I want the flash messages to be displayed when I add or delete items, but is there a way to make them fade out? In my view file, I have included the following code: <script> $(documen ...

The Sizzle.js error, "Uncaught TypeError: undefined (reading 'expr')," is causing some trouble

$.expr[':'].containsCaseInsensitive = function (n, i, m) { return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; }; .expr is not recognized. To ensure it's defined, I included a CDN link below: <script src=&qu ...

Updating the image source using JQuery dynamically

Within my index.php file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('.on').click(function ...

What is the specific user that IIS utilizes to gain access to files?

In my ASP.NET application, I am using some files located in the project directory such as licenses and logs. I need a method to verify file permissions, so I crafted this code snippet: public static bool IsCurrentUserHaveAccessToFile(string filePath, ...

Passing an array from a view to a controller in ASP.NET MVC without relying on Ajax

I need assistance with passing an array of strings from a view to a controller in asp.net mvc 5 without using Ajax. Can someone guide me through this? Here is the controller code, where the value needs to be received in packagelist[] public ActionResult ...

Selecting the initial option as the default in a drop-down menu

How can I use Jquery to add a new row and set the default value of a dropdown list? var selectVal = $(parent).children().first().find('select').find('option[selectedGivenTo="true"]').val(); var newSelect = $(parent).children().last ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Addressing Performance Challenges in Urban Rendering with ThreeJS

Issue: I am facing significant performance problems while rendering a scene using Three JS. The main issue arises from rendering a large number of simple geometries (11,107). (edit) Each building has a unique height based on elevation data, a distin ...