Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs Browser Tab Close Event

Tags:

reactjs

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.

like image 311
dhrDatt Avatar asked Apr 01 '16 11:04

dhrDatt


People also ask

How do you close a tab in react?

window. close() can be used only when window. open() is used.

How do you close a tab in Javascript?

window. top. close(); this will close the current tab for you.


2 Answers

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.

like image 57
Amid Avatar answered Sep 19 '22 14:09

Amid


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>         )     } } 
like image 24
Artur Barseghyan Avatar answered Sep 16 '22 14:09

Artur Barseghyan