We can detect a tab or window using the beforeunload event. This can be used to alert the user if some data is not saved on the page or if the user has mistakenly strayed from the current page by closing the tab or browser.
The addEventListener() method is used to configure a function whenever an event occurs. The beforeunload event is triggered just before a browser window/tab is closed.
Some browsers may choose not to display the confirmation box unless the user has interacted with the page.