Last active
February 11, 2020 21:08
-
-
Save kosmala007/1d05aefff77c529fe2ef5fedfed00a19 to your computer and use it in GitHub Desktop.
Script for prompt before leave form without saving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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