最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React call function before windowtab close - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 4

As 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();
});
发布评论

评论列表(0)

  1. 暂无评论