This content originally appeared on DEV Community and was authored by Tia Eastwood
Sorry I couldn't think of a shorter title!
Here is a useful little snippet for if you have a page like a checkout or a survey and you want to warn people about leaving the page before they've completed it.
window.onbeforeunload = (event) => {
if (whatever your condition is here) {
return true;
}
};
The alert gives the user the option to confirm or cancel their navigation. Alerts should never stop someone from leaving a page or closing their browser though; that's a big no-no.
An onbeforeunload event occurs when the document (the current page of your site/application) is about to be unloaded (closed/exited). A example of this would be someone closing the browser window or clicking a link to a different page.
Most browsers will show a default message like "changes you've made will not be saved". You can't edit this message, but it does the job as a warning. Due to this, you don't need to return any specific content or message in the function, just return true in order for it to work.
This function will be called when an onbeforeunload event occurs. If the condition inside is met, then the function will return true and the alert will be shown. So all you need to do is apply a condition to decide when the alert will be shown. For example, if using this in a React application, then the condition could be based on a certain state. For example:
const [isSurveyCompleted, setIsSurveyCompleted] = useState(false)
window.onbeforeunload = (event) => {
if (!isSurveyCompleted) {
return true;
}
};
// the alert will appear if the user tries to close the browser window because they haven't completed the survey.
There are other ways of achieving this sort of behaviour, such as using Prompt in react-router, but if you're just looking for a simple solution then I hope this helps! If you have anything to add, please leave a comment.
This content originally appeared on DEV Community and was authored by Tia Eastwood
Tia Eastwood | Sciencx (2021-05-11T14:01:23+00:00) How To Create A Simple Alert For An onbeforeunload Event (Closing Browser or Navigating Away From Page). Retrieved from https://www.scien.cx/2021/05/11/how-to-create-a-simple-alert-for-an-onbeforeunload-event-closing-browser-or-navigating-away-from-page/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.