Hi I want to know how to prompt a message on browser tab close. I am using Reactjs.
handleWindowClose(){ alert("Alerted Browser Close"); }, componentDidMount: function() { window.addEventListener('onbeforeunload', this.handleWindowClose); }, componentWillUnmount: function() { window.removeEventListener('onbeforeunload', this.handleWindowClose); }
this is what I have tried adding to my react component.Please guide me on how to proceed further.
window. close() can be used only when window. open() is used.
window. top. close(); this will close the current tab for you.
What you did is correct apart from the event name and the fact that alert will be blocked in that particular event.
You can show a message like this:
window.addEventListener("beforeunload", (ev) => { ev.preventDefault(); return ev.returnValue = 'Are you sure you want to close?'; });
Hope this helps.
Amid's answer worked well for me.
The way I used it:
class MyComponent extends Component { // Things to do before unloading/closing the tab doSomethingBeforeUnload = () => { // Do something } // Setup the `beforeunload` event listener setupBeforeUnloadListener = () => { window.addEventListener("beforeunload", (ev) => { ev.preventDefault(); return this.doSomethingBeforeUnload(); }); }; componentDidMount() { // Activate the event listener this.setupBeforeUnloadListener(); } // Render method. render() { return ( <div>My component</div> ) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With