1window.addEventListener('beforeunload', (event) => {
2 event.returnValue = `Are you sure you want to leave?`;
3});
4
1let formChanged = false;
2myForm.addEventListener('change', () => formChanged = true);
3window.addEventListener('beforeunload', (event) => {
4 if (formChanged) {
5 event.returnValue = 'You have unfinished changes!';
6 }
7});
8
1const pendingOps = new Set();
2
3window.addEventListener('beforeunload', (event) => {
4 if (pendingOps.size) {
5 event.returnValue = 'There is pending work. Sure you want to leave?';
6 }
7});
8
9function addToPendingWork(promise) {
10 pendingOps.add(promise);
11 const cleanup = () => pendingOps.delete(promise);
12 promise.then(cleanup).catch(cleanup);
13}
14