azat-co / react-quickly

Source code for React Quickly [Manning, 2017]: Painless Web Apps with React, JSX, Redux, and GraphQL 📕
http://reactquickly.co
MIT License
544 stars 423 forks source link

ch05 listing 5.4: confirm dialog not displayed on leaving or closing tab #48

Closed oneno closed 2 years ago

oneno commented 2 years ago

This problem appeared in recent browsers ( firefox 95, brave version 1.33.106 Chromium: 96.0.4664.110, gnome web 41.3 ...).

The following article suggests using page visibility to not lose user or app state: https://www.igvita.com/2015/11/20/dont-lose-user-and-app-state-use-page-visibility/

oneno commented 2 years ago

Made the following changes to script.jsx to have confirm message display whenever tab lost focus:

class Note extends React.Component {
    confirmLeave(e) {
      let confirmationMessage = 'Do you really want to close?'
      //e.returnValue = confirmationMessage     // Gecko, Trident, Chrome 34+
      //e.returnValue = confirm(confirmationMessage)     // Gecko, Trident, Chrome 34+
      //return confirmationMessage              // Gecko, WebKit, Chrome <34

      if (window.confirm(confirmationMessage, false)) {
        // allow tab to lose focus or be closed
      } else {
        e.preventDefault()
      }

      e.returnValue = confirmationMessage
      return confirmationMessage
    }
    componentDidMount() {
      console.log('Attaching confirmLeave event listener for visibilitychange')
      //window.addEventListener('beforeunload', this.confirmLeave)
      window.addEventListener('visibilitychange', this.confirmLeave)
    }
    componentWillUnmount() {
      console.log('Removing confirmLeave event listener for visibilitychange')
      //window.removeEventListener('beforeunload', this.confirmLeave)
      window.removeEventListener('visibilitychange', this.confirmLeave)
    }
    render() {
      console.log('Render')
      return <div>Here will be our input field for notes 
        (parent will remove in {this.props.secondsLeft} seconds)</div>
    }
  }

Instead of displaying confirm dialog, a message displayed to the page informing the user is a better approach.

If there are edits waiting to be saved and the user doesn't confirm changes, edits would be lost.