Steps to display the leave site prompt during the beforeunload event once a function has finished running

While facing a challenge with executing synchronous Ajax methods in page dismissal events, I discovered that modern browsers no longer support this functionality in the "beforeunload" event. To work around this issue, I implemented a new promise that resolves only after the Ajax methods have completed successfully.

This solution works perfectly when triggered by a button click. However, during the page unload event, the function pauses due to the prompt asking, "Leave site? changes made may not save." Unfortunately, clicking on "leave" prevents the function from running.

Do you have any suggestions for overcoming this obstacle?

//Index.html

<button type="button" onclick="checkAjaxWithAsync()">Check with Async</button>

//Index.js

var isUpdated = false;
        var interval;
        var data;
        var newHandle;

        $(document).ready(function () {
            $(window).on("beforeunload", async function (event) {
                await checkAjaxWithAsync();
            })
        });

        function ajaxCall() {
            $.ajax({
                type: 'POST',
                url: '@(Url.Action("CheckAjax"))',
                async: true,
                success: function (result) {
                    console.log(result);
                    isUpdated = true;
                    clearInterval(interval);
                },
                error: function () {
                    debugger;
                }
            }).done(function () {
                console.log('After done');
            });
            console.log('After ajax');
        }

        async function checkAjaxWithAsync() {
            isUpdated = false;
            await processFunction();
            console.log('is updated:', isUpdated);
            console.log('Hi From Do IT');
        }

        async function waitUntil() {
            return await new Promise(resolve => {
                const interval = setInterval(() => {
                    if (isUpdated) {
                        resolve('completed');
                        clearInterval(interval);
                    };
                }, 1000);
            });
        }

        async function processFunction() {
            ajaxCall();
            await waitUntil();
            console.log('after interval');
        }
    

//HomeController.cs

public class HomeController : Controller
        {
            public IActionResult Index()
            {
                return View();
            }

            [HttpPost]
            public string CheckAjax(object data)
            {
                System.Threading.Thread.Sleep(1000 * 10);
                return "Hello";
            }
        }
    

Answer №1

Based on the details provided, it seems that implementing this requirement may not be feasible. The built-in behavior is specifically designed to limit significant alterations for security reasons.

The main function of the beforeunload feature is to give users the opportunity to save any changes they have made before potentially losing them.

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

JavaScript not properly rendering CSS styles

If I insert the following HTML statically, the CSS style is correctly applied. HTML: <li class="connector"> <a href="#"> <img src="css/images/temp/connector2.png" alt="" width="192" height="192"> <span class="sr-only"& ...

Instructions for retrieving data from a weather API using JavaScript

Hello amazing Stackoverflow community! I need your help to figure out how to extract data from a weather REST API using JavaScript. I'm struggling to fetch the weather condition and date/time information from this API. { info: { _postman_i ...

Issue with ThemeManager in Material UI & React: Constructor is not valid

Currently, I am integrating Material UI into a small React application, but I suspect that the tutorial I am following is outdated and relies on an older version of Material UI. The error _materialUi2.default.Styles.ThemeManager is not a constructor keeps ...

Why is it that when I refresh a page on localhost, the file download gets stuck until I close the page?

As I work on my HTML/JS files hosted on localhost with Node, I've noticed that when I make changes to the code, Webpack automatically rebuilds the JS files. However, there are times when, after making updates and trying to refresh the page, the downl ...

Construct a structure containing the key/value pairs of cells within an HTML table row using JavaScript

I'm completely new to JavaScript so please be patient with me; I'm not even sure if I'm searching for the solution correctly. Despite spending hours googling and experimenting, I still can't get it to work. My issue is related to an HT ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

Is there a simple method to refresh a JSP or Spring MVC page using AJAX?

I'm tackling a seemingly basic question in Java web development here, but I could use some guidance. How can I refresh data on a JSP page? I understand the fundamentals (utilize jQuery for AJAX, Spring MVC for the "Controller" & handle data reque ...

What is the best way to structure 2 variables for a single ajax request to ensure the data can be efficiently utilized?

I need help with a click event... $('#save').on('click', function(){ var employee = $('#employee').serialize(); // details from form fields like name, phone, email var training = []; // initialize empty array $ ...

Tips for adjusting the maximum height of the column panel within the DataGrid element

I'm trying to adjust the max-height of a column panel that opens when clicking the "Columns" button in the Toolbar component used in the DataGrid. I am working with an older version of @material-ui/data-grid: "^4.0.0-alpha.8". https://i.stack.imgur.c ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

What is the process for javascript selecting a remote-data service?

I recently purchased a new app and am diving into Javascript and AngularJS for the first time. As I try to navigate through the code, I find myself puzzled by how the function in homeService.js is able to utilize remote-data.service.js. Featured below is ...

Transform the outcome of Request() into a variable

I'm currently working with the following code snippet: request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){ var req_data = JSON.parse(body); conso ...

The multiple checkbox filter is not showing the right results

I am currently working on a code snippet, but unfortunately, I am facing some challenges in getting it to function as expected. The issue lies with the checkboxes that are meant to filter the list and update the screen live using AJAX. While the multiple ...

Verify the ability to view a webpage

I am currently working on creating a method to check if data access is equal to next.data.access. Since it's an array, I cannot use the includes method. It would be enough for just one of the data access values in the array to return true. auth.guard ...

Only trigger the function for a single bootstrap modal out of three on the current page

I'm facing a challenge on a page where I have 3 bootstrap modals and I need to trigger a function only for one modal while excluding the other two. $("body").on("shown.bs.modal", function() { alert('modal Open'); //this alert should ...

Encountering a problem when trying to utilize material-ui icons in a React application

After installing the Material-UI core and icons packages using npm install @material-ui/core and npm install @material-ui/icons in my React app, I tried to use the FileUploadIcon. Here's how I imported it: import { FileUploadIcon } from '@materia ...

It appears that the lodash throttle function is not being invoked

I recently started utilizing lodash's throttle function to control the number of calls made to an API. However, I am facing difficulties as the call doesn't seem to be triggered successfully. Below is a simplified version of what I have attempte ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

The update function in model.findByIdAndUpdate() is failing to make changes

I am struggling to update a user model with new data using findByIdAndUpdate(). Despite my efforts, the model does not reflect the changes made. Below is the code snippet where I am attempting to use findByIdAndUpdate() to add an object: const User = ...

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...