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