I’m very keen to add a feature where if a user tries to close their tab or window without saving their data, the browser pauses and asks them if they’re sure they want to leave without saving.
Is there any way - easy or complicated - to implement this? Would be a big help
If you have the site under your own domain, you can create a custom element that prompt an alert on beforeunload.
Of curse, you’ll have to pass the mode (‘saved’ / ‘edit’) to the element by element.setAttribute.
Whether or not it is complicated depends on your knowledge.
It’ll take a few minutes for someone who knows what to do. If you never worked with custom elements it might take you more.
Thanks so much for the advice! This worked perfectly.
Implementation below for anyone interested…
I have added a custom element called #leaveWithoutSaving in the footer of my site. Any time I want it to trigger the prompt I run the following snippet:
// parameter which tetermines whether leave without saving prompt is triggered
let unsaved = false
class leaveWithoutSaving extends HTMLElement {
constructor() {
super();
}
// call back runs when an attribute is changed
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'unsaved') {
unsaved = true;
} else if (name === 'saved') {
unsaved = false;
}
}
static get observedAttributes() {
return ['unsaved', 'saved'];
}
}
customElements.define('leave-without-saving', leaveWithoutSaving);
// function which triggers the leave without saving prompt
window.onbeforeunload = function () {
if (unsaved === true) {
return 'Are you sure you want to leave without saving?';
}
};
P.S. You should go for the single-attribute approach, because your code doesn’t cover all scenarios.
For example, if the user made some changes, saved them, and then made some other changes and tried to leave without saving the new changes.
Your code will not catch it (because the ‘unsaved’ attribute value hasn’t changed since the previous iteration - unless you set its value to be a random big number or the current time converted to string).
My code will catch it.