Home > Software engineering >  Synchronous ajax request in beforeunload event alternative to support Edge chromium
Synchronous ajax request in beforeunload event alternative to support Edge chromium

Time:10-12

I have to make a synchronous ajax request in beforeunload event, but it is throwing an error as synchronous ajax request are not supported in chromium browsers during page unload events.

What could be the alternative to make a synchronous ajax request during page unload event cycle.

window.on('beforeunload',function(){
    $.ajax({
         url:'@Url.Action("ActionName","ControllerName")',
         async:false,
         data:formData,
         success:function(){
            //Success logic
         },
         error:function(){
           //Failure logic
         }
    });

});

DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load:

Note: navigator.sendBeacon() is asynchronous by default, but i need to have a synchronous request in page dismissal.

Any suggestions?

CodePudding user response:

Synchronous XMLHttpRequest has been deprecated, you can refer to this doc. Blink has removed support for sync XHR from page dismissal events (beforeunload and unload) and you simply can't do that anymore in chromium browsers.

The modern ways are to use sendBeacon and fetch keepalive as workarounds. For more information, you can refer to this tweet and this thread. If you don't use these workarounds, I think there's no other way.

  • Related