Skip to content

Commit 760a87c

Browse files
authored
Merge pull request #264 from wpengine/previews-unsaved-changes-warning
fix: add unsaved changes warning
2 parents 2ab27d5 + e65ce73 commit 760a87c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

plugins/hwp-previews/assets/js/hwp-previews.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
document.addEventListener("DOMContentLoaded", () => {
2+
// --------------------------------------------------------
3+
// Parameter buttons
4+
// --------------------------------------------------------
5+
26
const buttons = document.querySelectorAll(".hwp-previews-insert-tag");
37
const input = document.querySelector(".hwp-previews-url");
48

@@ -40,4 +44,36 @@ document.addEventListener("DOMContentLoaded", () => {
4044
for (const button of buttons) {
4145
button.addEventListener("click", insertTag);
4246
}
47+
48+
// --------------------------------------------------------
49+
// Unsaved changes warning
50+
// --------------------------------------------------------
51+
52+
// Select the form to monitor for changes
53+
const formElement = document.querySelector("form");
54+
55+
function getFormState(form) {
56+
const data = new FormData(form);
57+
return JSON.stringify(Array.from(data.entries()));
58+
}
59+
60+
// Save the initial state of the form for later comparison
61+
const initialState = getFormState(formElement);
62+
63+
// Warn the user if they try to leave with unsaved changes
64+
function beforeUnload(e) {
65+
const formState = getFormState(formElement);
66+
67+
if (formState !== initialState) {
68+
e.preventDefault();
69+
e.returnValue = true;
70+
}
71+
}
72+
73+
window.addEventListener("beforeunload", beforeUnload);
74+
75+
// Remove the warning on submit so it doesn't appear when saving
76+
formElement.addEventListener("submit", function () {
77+
window.removeEventListener("beforeunload", beforeUnload);
78+
});
4379
});

0 commit comments

Comments
 (0)