commit: 71622e2932bc05ba53209f9d765752d547c78520
parent edf5e36bf877a49daefbb742fea93cafaadc1031
Author: tusooa <tusooa@kazv.moe>
Date: Thu, 22 Aug 2024 21:06:19 -0400
Save draft on window's beforeunload event
Diffstat:
1 file changed, 21 insertions(+), 0 deletions(-)
diff --git a/src/components/post_status_form/post_status_form.js b/src/components/post_status_form/post_status_form.js
@@ -354,10 +354,20 @@ const PostStatusForm = {
handler () {
this.statusChanged()
}
+ },
+ savable (val) {
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#usage_notes
+ // MDN says we'd better add the beforeunload event listener only when needed, and remove it when it's no longer needed
+ if (val) {
+ this.addBeforeUnloadListener()
+ } else {
+ this.removeBeforeUnloadListener()
+ }
}
},
beforeUnmount () {
this.maybeAutoSaveDraft()
+ this.removeBeforeUnloadListener()
},
methods: {
statusChanged () {
@@ -785,6 +795,17 @@ const PostStatusForm = {
this.abandonDraft().then(() => {
this.$emit('can-close')
})
+ },
+ addBeforeUnloadListener () {
+ this._beforeUnloadListener ||= () => {
+ this.saveDraft()
+ }
+ window.addEventListener('beforeunload', this._beforeUnloadListener)
+ },
+ removeBeforeUnloadListener () {
+ if (this._beforeUnloadListener) {
+ window.removeEventListener('beforeunload', this._beforeUnloadListener)
+ }
}
}
}