-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWarningBeforeUnload.js
More file actions
36 lines (31 loc) · 1.31 KB
/
WarningBeforeUnload.js
File metadata and controls
36 lines (31 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class WarningBeforeUnload {
constructor(options = {}) {
this.selector = options.selector || 'form';
this.form = options.form || document.querySelector(this.selector);
this.onInput = options.onInput || false;
this.onSubmit = options.onSubmit || function() {
this.form.addEventListener('submit', () => this.preventUnload = false);
};
if(this.form) {
Array.from(this.form).forEach(item => item.dataset.prevalue = this.prevalue(item));
this.onInput ? this.form.addEventListener('input', () => this.addBeforeUnload()) : this.addBeforeUnload();
this.preventUnload = true;
this.onSubmit();
} else {
throw 'WarningBeforeUnload: Form not found';
}
}
prevalue(item) {
return ['checkbox', 'radio'].includes(item.type) ? (item.checked ? 1 : 0) : item.value;
}
getFormState(event) {
if(this.preventUnload) {
Array.from(this.form).forEach(item => {
typeof item.dataset.prevalue == 'undefined' || item.dataset.prevalue != this.prevalue(item) ? event.preventDefault() : true;
});
}
}
addBeforeUnload() {
addEventListener('beforeunload', event => this.getFormState(event), { capture: true });
}
}