From 71622e2932bc05ba53209f9d765752d547c78520 Mon Sep 17 00:00:00 2001 From: tusooa Date: Thu, 22 Aug 2024 21:06:19 -0400 Subject: [PATCH] Save draft on window's beforeunload event --- .../post_status_form/post_status_form.js | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/components/post_status_form/post_status_form.js b/src/components/post_status_form/post_status_form.js index 63452747..1ae98549 100644 --- 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) + } } } }