This is my first post ever on any blog/site i am not a good writer. I am junior ASP.NET software engineer recently i am working in React for front end development.
Yesterday was writing a function in JavaScript for on window closed. function responsibility was to send xhr call to server.
Here is my source code.
// binding beforunload event
componentDidMount() {
if (window.addEventListener) {
window.addEventListener('beforeunload', this.onUnload, false);
} else if (window.attachEvent) {
window.attachEvent('onbeforeunload', this.onUnload);
}
}
// call api function 'unlock'
onUnload() {
unlock();
}
// api
export function unlock(Id) {
return axios
.get(UNLOCK(Id))
.then((data) => data);
}
It was working fine for chrome but it was not working for IE.
I spend a lot of time to debug this issue but did not succeed. after that one of my colleague recommend me to send an sync call to the server because of asynchronous browser did not wait for response. after spend a lot time of arguing with him i implement and it works.
After change async to sync
export function unlock(Id) {
// use jQuery ajax call becaus axios does not provide {async: false} option
window.jQuery.ajax({
type: 'GET',
url: UNLOCK(Id),
async: false,
success(data) {
//code
},
});
}
Discussion
My understanding is when unlock function calls on window close. function should send xhr request to server after that browser tab should be closed.
In my case i don't need the response of xhr call.
@erildo Shuli if you don't know the answer please don't comment :) Thanks.