【Vue.js】Issue an anti-withdrawal alert when updating the page, etc.

I want to issue an alert such as "Input contents are discarded" when updating input pages or unintentional page transitions, such as user data registration and editing pages. Use WindowEventHandleers.onbeforeunload.


WindowEventHandlers.onbeforeunload | MDN
onbeforeunload は WindowEventHandlers ミックスインのプロパティで、 beforeunload イベントを処理する event handler です。このイベントはウィンドウでリソースを unload (en-US) しようとするときに発生します。この時点では文書はまだ表示されており、...

The event that occurs when the screen is closed. This event allows you to alert you when closing the screen, transitioning the screen, or pressing the update button.

He's like this. I'm sure he's seen it.

For example, on the registration and editing page of user information, you can reduce accidents such as "I accidentally transitioned the page and when I returned, the input content was lost".


Set the window.onbeforeunload event when displaying the page and fill the event with null when the page isdestroyed.

mounted: function () {
    window.onbeforeunload = function () {
      Return' unsedued data is discarded. '
destroyed () {
    window.onbeforeunload = null

Known issues

We know it doesn't work with Safari on iOS. In that environment, it seems good to use the pagehide event.

Window: pagehide event - Web APIs | MDN
The pagehide event is sent to a Window when the browser hides the current page in the process of presenting a different page from the session's history.

I haven't .js Vue's environment yet, so I'll try it out and add it to it.