简体   繁体   中英

Show modal window on click of tab close

I am using react hook useBeforeunload to detect tab close event and want to display a modal window but I am stuck with below code. On click of close icon(X), it's not showing modal window which I am setting to true with setVisible and simply exiting the tab.

import { useBeforeunload } from 'react-beforeunload';

 const [visible, setVisible] = useState(false);

 const showModalWindow = (e) => {
  setVisible(true);
 }

useBeforeunload((e) => {
    e.preventDefault();
    showModalWindow();
  });

Any suggestions to make this work will be really helpful. Thanks in advance :)

First problem, useBeforeUnload is expecting you to return a string in your handler function.

Second problem, the usebeforeunload eventListener (which this package is using) will in most modern browsers not display a modal that you are trying to render. What happens instead is that the browsers will show a native dialogue asking you if you are sure you want to leave the page.

So if you make your event handler return a string , you should probably see the native dialogue if you try to close the tab.

You can find more info here:

https://github.com/jacobbuck/react-beforeunload

https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM