Limit User from closing pop-up till it loads completely

I am trying to trigger some operations on page unload. My page contains a form with a submit button. On submitting the form it reloads the page (Basically a postback) and there are some operations that are performed. Lets say these operations take a minute or two to complete.
Now I want to show an alert to users if they try to close the tab while the page is still processing. But I don’t want to show the alert on click of submit button.
This is happening currently because when I click on submit button the form is submitted and the beforeunload event is triggered.

I want the before unload event to trigger only if the page unload is done by closing the tab and not by the click on submit button.
Any ideas on how it can be implemented?