Recently, I encountered the requirement of closing the browser to prompt the user to save when the user’s modification is not saved, similar to the following figure. This article records the knowledge points used.

window.onbeforeunload

Details are described in the onbeforeUnload MDN document. This event is triggered when a window is about to be unloaded (closed). The page document is still visible and the default action for the event can be cancelled. Page refreshes and switches also trigger this function.

Usage:

window.onbeforeunload = () => {
  if(hasChanged)
    return "Discard current unsaved content and close the page?";
}
Copy the code

window.onunload

The onUnload method has the same usage and function as onbeforeUnload

The comparison is as follows:

Onbeforeunload browsers are compatible and supported by all major browsers. Onunload compatibility poor onbeforeUnload executes before onUNLOAD, which can also prevent onunload from executing.

Navigation guard

But onbeforeUnload sometimes does not work on Vue single-page sites because single-page switching does not trigger window unload events. So vue-Router navigation guards are used to implement this, using a guard within the component. Usage:

beforeRouteLeave: function(to, from , next){
  if (hasChanged) {
    this.$confirm('Discard the current unsaved content and close the page? '.'tip', {
      confirmButtonText: 'sure',
      cancelButtonText: 'cancel'.type: 'warning'
    }).then(() => {
      next()
    }).catch(() => {
      next(false)}); }else {
    next()
  }
}
Copy the code