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

Utilize Google Home to browse through nearby websites and respond to inquiries by incorporating Javascript

Can Google Home be programmed to read from a local webpage and provide answers based on the content of that page through Javascript? ...

Utilizing jQuery to create a recursive AJAX poll with setTimeout to regulate the polling frequency

$(document).ready(function() { (function pollUsers() { setTimeout(function() { $.ajax({ url: "/project1/api/getAllUsers", type: "GET", success: function(userData) { ...

Send multiple messages using PHPMailer

Today an error occurred. I have created a PHPMailer object where a user registers and the application sends a mail notification. I have implemented ajax to return data type json, but keep receiving several messages. SERVER -> CLIENT: 220 smtp.gmail.com ...

What is the best way to integrate jQuery Masonry with ES6 modules?

Attempting to utilize the npm package https://www.npmjs.com/package/masonry-layout Following the installation instructions, I executed: npm install masonry-layout --save Then, in my file, import '../../../node_modules/masonry-layout/dist/masonry.p ...

"Utilizing Dynamic Dropdown Options Pulled from Database and Automatically Refreshing List upon

I am facing a dilemma with displaying dropdown menus for Provinces and Cities, both of which have values coming from the database. While I can easily list the values for Provinces by querying all of them, my issue arises when it comes to displaying Cities. ...

Ways to verify if an element includes a specific class in JavaScript

When the mouse hovers over each paragraph within the DIVs with the "change" class, the font color should turn red, and revert back to black when the mouse is not on them. Here's my current code: var paragraphs = document.getElementsByTagName('p& ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...

What's the reason for not receiving any outputs from php?

$('#registerForm').submit( function() { callAjaxSubmitMethod(this); //event.preventDefault(); } ); This code snippet is a part of my DOM ready function. function callAjaxSubmitMethod(form) { $.ajax({ type ...

Ways to resolve axios promise

My current task involves working on a GET request from an API. Upon receiving the response shown in the image, I noticed that the data presented in the promise is accurate. My goal is to display the letters and their corresponding promise data within the H ...

jquery is unable to locate text

UPDATE: I have recently implemented a function that calculates and displays the length of a certain element, but it currently requires user interaction to trigger it: function check() { alert($("#currentTechnicalPositions").html().length); } After s ...

Fetching the name of a JSON object in JavaScript converted to a string

Is there a way to retrieve the name 'muxEnvironments' as a string from the object? I need it in order to analyze and compare the content type. When I use console.log(obj), the entire object is displayed. My objective is something like this: jso ...

Pass the callback function `cb_func` as a parameter to the `foobar` function when calling it in the `onclick`

I have an element that I want to trigger an onclick event with a callback function. Here is the code snippet: function cb_func() { alert("hello world!"); } function foobar(i, cb) { // do something if (cb != undefined) cb(); } onclic ...

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

Merge floating and absolute positioning techniques

Creating a calendar exhibiting all events in one div requires precise positioning based on the values of top and height. Let me demonstrate this concept. In the image below, both 6am events are aligned vertically. This alignment issue can be resolved by u ...

Unpredictable order of replies retrieved using $http.get

I am struggling to create a function that sends multiple requests to the server based on the number of Ids in the idArray. The issue I am encountering is that the data being pushed into the dataArray does not align with the corresponding Ids of the idArr ...

Tips for referencing a string in JavaScript

I am trying to use the showmodal method, but I keep getting an error when passing a string. It works fine with integers, but how can I pass a string in JavaScript? <script> var table = ' <table id="example" class="table table-striped " w ...

Designing architecture for NPM packages in TypeScript

I am currently developing multiple NPM packages using TypeScript and I am exploring the most effective strategies for supporting various target architectures. When compiling to ES3, there is extensive support but it comes with additional boilerplate for c ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Making API calls using JavaScript

I'm struggling with understanding how to approach this problem in javascript. Here is the question along with the details. I would appreciate any assistance. QUERY We have a server backend that provides two endpoints: /GetLocalPressReleases and /Get ...

Making a REST API call with an ID parameter using Angular

I am currently working on an Angular application that interacts with a REST API. The data fetched from the API is determined based on the customer ID, for example: api/incident?customer_id=7. I am unsure of how to incorporate this into the API URL and serv ...