Skip to content

Instantly share code, notes, and snippets.

@kosmala007
Last active February 11, 2020 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosmala007/1d05aefff77c529fe2ef5fedfed00a19 to your computer and use it in GitHub Desktop.
Save kosmala007/1d05aefff77c529fe2ef5fedfed00a19 to your computer and use it in GitHub Desktop.
Script for prompt before leave form without saving
class DontLeaveMeAlone {
constructor(formElem) {
this.formElem = formElem;
this.formCheckSum = this.getFormCheckSum();
// Events
this.boundBeforeunloadEventHandler = e => this.beforeunloadEventHandler(e);
window.addEventListener('beforeunload', this.boundBeforeunloadEventHandler);
this.formElem.addEventListener('submit', (e) => this.submitEventHandler(e))
}
beforeunloadEventHandler(e) {
let currentFromCheckSum = this.getFormCheckSum();
if (this.formCheckSum !== currentFromCheckSum) {
e.preventDefault();
e.returnValue = '';
}
}
submitEventHandler(e) {
window.removeEventListener('beforeunload', this.boundBeforeunloadEventHandler);
}
getFormCheckSum() {
const data = new URLSearchParams(new FormData(this.formElem)).toString();
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment