This is the seventh day of my participation in the More text Challenge. For details, see more text Challenge

Hello everyone, I’m Daotin, captain of the front end, want to get more exciting content of the front end, follow me, unlock the new position of the front end growth.

The following text:

Problem description

For some interfaces that need to fill in user information, when the user clicks back, or refreshes the interface, or closes the interface, it is necessary to timely remind the user that the current page has filled in the content. If the user returns or refreshes the interface, the content will be lost. Remind the user and let the user decide what to do.

The solution

Beforeunload event helps you do this.

The beforeUnload event is triggered when the browser window closes or is refreshed. The current page will not be closed directly, you can click the OK button to close or refresh, or cancel.

This event enables the web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser will navigate to the new page, otherwise the navigation will be cancelled.

According to the specification, to display the confirmation dialog, the event handler needs to call preventDefault() on the event.

Note that not all browsers support this method, and some require the event handler to implement one of the two legacy methods instead:

  • Assign a string to the eventreturnValueattribute
  • Returns a string from the event handler.

These two methods, which were used to customize the text message to be displayed in confirmation dialogs, have been deprecated, and most browsers do not support custom dialog text messages.

Code sample

window.addEventListener('beforeunload'.(event) = > {
  // The confirmation dialog box is displayed
  event.preventDefault();
  // For compatibility processing, Chrome needs to set the returnValue
  event.returnValue = ' ';
});
Copy the code

Special remind

  • To avoid unexpected pop-ups, the beforeUnload event is not triggered when refreshing or closing unless the page has been interacted with (a mouse click on the page).

  • The confirmation dialog box cannot display a custom string. Some browsers used to be able to display user-defined messages. However, this method has been deprecated and is no longer supported in most browsers.


Recent popular articles:

  • Picture waterfall flow, so easy
  • 4 Common Cross-domain Ajax Solutions (Easy to understand)
  • Vue.js Naming Style Guide (easy to remember version)

Above, if you think it helps you, just click “like”, so Daotin also has the power to update, thank you! ~~~ I heard that people who like “like” will have good luck in a month ~~