SoFunction
Updated on 2025-04-12

Vue project uses js to listen to the browser to close, refresh and back events to achieve the method of closing, refreshing and backing events

Business scenarios

In web application development, we often encounter the need: suddenly closing, refreshing or backing the browser during the process of user performing key operations, such as submitting forms, paying transactions, etc., may lead to incomplete operation or data loss. In order to improve user experience and ensure the integrity of application data, we need to reasonably use JavaScript to listen to browser close, refresh, and back events and make corresponding processing.

Implementation plan

Listen to beforeunload event

beforeunloadEvents are triggered when the page is about to be uninstalled, which usually occurs before the user closes or refreshes the page. We can use this event to prompt the user to confirm whether they really need to leave the current page.

('beforeunload', function (e) {
    // Prompt methods that are compatible with different browsers    var confirmationMessage = 'Are you sure you want to leave?  ';
     = confirmationMessage;  // Gecko, Trident, Chrome 34+
    return confirmationMessage;           // Gecko, WebKit, Chrome <34
});

Listen to unload events

When the document is completely uninstalled,unloadThe event will be triggered. This event can be used to perform some cleaning operations, such as clearing cookies, logging, etc.

('unload', function(event) {
    // Perform some cleaning operations});

Listen to the browser back button event

The browser back button triggerspopstateEvents, it is usually used in conjunction with HTML5's history API. In Vue project, if you usevue-routerTo manage routes, you can listen for route changes as follows to handle the behavior of the back button:

((to, from, next) => {
    // Backward logic can be handled here    // to and from are routing objects    next(); // Make sure to call the next() method, otherwise the hook will not be resolved});

In addition, you can also listen directlypopstateEvents to handle back operations:

methods:{
	onPopState(e) {
		// Listen to the browser fallback event (the confirm used here is customizable)		if (confirm('The data may be lost when leaving the current page. Are you sure you leave the current page?  ')) {
			// Click OK to return			('popstate', )
			(-1)
		} else {
			// Click Cancel and do not return			(null, null, )
		}
	},
},
 mounted() {
		// Add popstate event listening		(null, null, );
		('popstate', );
   },
beforeDestroy() {
	// Remove popstate event listening before component destruction	('popstate', )
}

Distinguish between browser refresh and close

For the listening of the browser refresh event, although it will triggerbeforeunloadEvents, but sometimes we need to distinguish whether the page is refreshed or closed. This can be achieved through some tricks, such as usingsessionStorage

if ( == .TYPE_RELOAD) {
    ("This is an operation to refresh the page");
} else {
    ("This is a new access page operation");
}

Please note thatFeatures are no longer recommended because they are abandoned and not supported by all browsers. InsteadNavigation Timing API, Despite this, this API cannot directly detect refresh events.

When using the above events, we should be careful to avoid hindering the normal operation of the user. in particularbeforeunloadEvents, if not very necessary, are best not to use, as it may affect the user experience. We should only use warning prompts if users may lose important data.

Appendix: How to distinguish between browser refresh and closing

Knowledge points

The browser closes the two events beforeunload and unload;

The browser refresh executes three events beforeunload, unload, and load;

Ideas

Although refreshing and closing will go through onbeforeunload and onunload, it may be that the internal mechanism needs to be prepared before loading a new page, so when the refresh event is executed to the onunload event, it will take longer than the closing event.

Therefore, by using the time difference, we can determine whether the browser is refreshed or closed. When the browser executes beforeunload, we can give a start time and an end time when the browser executes unload; we can judge the time difference; I set 5 milliseconds to distinguish the browser's closing and refreshing, and it is best to test the specific time yourself;

Code

 mounted() {
    let beginTime = 0; //Start time    let differTime = 0; //Time difference     = function () {
      differTime = new Date().getTime() - beginTime;
      if (differTime <= 5) {
        ("This is closed");
      } else {
        ("This is a refresh");
      }
    };

     = function () {
      beginTime = new Date().getTime();
    };
  },
};

I personally test it as effective

Summarize

This is the article about how to use the JS monitoring browser to close, refresh, and back events to the vue project. For more related contents of the vue JS monitoring browser to close, refresh, and back events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!