Home > Net >  How to show leave site? prompt in before unload event only after a function completes its execution
How to show leave site? prompt in before unload event only after a function completes its execution

Time:10-11

I have to execute a synchronos ajax method in page dismissla events, but modern browsers doesn't support to execute synchronos methods in beforeunload event anymore.

For that i have implemented a new promise that will resolve only after ajax methods completes its execution, it works fine in button click.

But in page beforeunload event, due to the prompt "Leave site? changes made may not save", the function halts its execution.

When user clicks on leave, it doesn't get executed.

Any suggestions?

//Index.html

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

//Index.js

    var isUpdated = false;

    var interval;
    var data;
    var newHandle;
    //Save report as HTML with file name...

    $(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";
        }
    }

CodePudding user response:

According to your description, I am afraid that this requirement cannot be implemented. Because this is built-in behaviour, designed to only allow very minimal changes for security purposes.

The primary purpose for the beforeunload is for things like allowing the users the option to save changes before their changes are lost.

  • Related