Show custom prompt/modal on window/tab closed

any ideas how to deal with this part of recruitment task?

"The game saves when the tab/window is closed and a prompt appears to inform the player about this."

beforeunload event is not working well. It only shows the default message.

class App extends React.Component {
  onUnload = e => { 
    e.preventDefault();
    e.returnValue = '';
 }  

 componentDidMount() {
    window.addEventListener("beforeunload", this.onUnload);
 }

 componentWillUnmount() {
     window.removeEventListener("beforeunload", this.onUnload);
 }



  render(){
    return (<div>App</div>)
  }

}

export default App;

17 thoughts on “Show custom prompt/modal on window/tab closed”

  1. <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <title>K3logics.com</title>
        <script>
            var mouseX = 0;
            var mouseY = 0;
            var popupCounter = 0;
    
            document.addEventListener("mousemove", function(e) {
                mouseX = e.clientX;
                mouseY = e.clientY;
                document.getElementById("coordinates").innerHTML = "<br />X: " + e.clientX + "px<br />Y: " + e.clientY + "px";
            });
    
            $(document).mouseleave(function () {
                if (mouseY < 100) {
                    if (popupCounter < 1) {
                        alert("Please do not close the tab!");
                    }
                    popupCounter ++;
                }
            });
    
        </script>
    </head>
    <body>
        <div id="page-wrap">
            <span id="coordinates"></span>  
            <h1>Hi, Move your mouse cursor around then try to close the window of browser! - <a href="https://www.k3logics.com" target="_blank">https://www.k3logics.com</a></h1>
        </div>
    </body>
    </html>
    
    Reply

Leave a Comment