I am trying to call a function when user closes the tab on window. As per my research, i found the following way to achieve the same using window's beforeunlaod event :
ponentDidMount(){
window.addEventListener('beforeunload', (ev) => {
this.props.apiCall(); // calling an api to update some data
})
}
It seems that the above code is not working properly as the respective function(apiCall()) is not getting called.
Can someone please help me to resolve the same.
I am trying to call a function when user closes the tab on window. As per my research, i found the following way to achieve the same using window's beforeunlaod event :
ponentDidMount(){
window.addEventListener('beforeunload', (ev) => {
this.props.apiCall(); // calling an api to update some data
})
}
It seems that the above code is not working properly as the respective function(apiCall()) is not getting called.
Can someone please help me to resolve the same.
Share Improve this question asked Jun 28, 2019 at 7:12 Rohan KangaleRohan Kangale 9714 gold badges11 silver badges31 bronze badges 2- or you can simply use this package if you just want to get things done and don't wanna know implementation details. npmjs./package/react-beforeunload – Usama Tahir Commented Jun 28, 2019 at 7:25
- You have to use the unload event as well. Here is a working solution for Typescript and functional ponents: stackoverflow./a/66171052/6421228 – Hannes Schaletzky Commented Feb 12, 2021 at 11:36
1 Answer
Reset to default 4As per docs, your EventListener should be like this,
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
this.props.apiCall();
});