@stimulus-library/controllers
Version:
A library of useful controllers for Stimulus
30 lines (29 loc) • 1.13 kB
JavaScript
import { BaseController } from "@stimulus-library/utilities";
import { useEventListener } from "@stimulus-library/mixins";
export class ConfirmNavigationController extends BaseController {
get _message() {
return this.hasMessageValue ? this.messageValue : "Do you want to leave this page? Changes you made may not be saved";
}
connect() {
window.onbeforeunload = () => this._message;
useEventListener(this, window, "popstate", this.confirmNavigation);
useEventListener(this, window, "submit", this.allowSubmit);
useEventListener(this, window, ["turbolinks:before-visit", "turbo:before-visit"], this.confirmTurboNavigation);
}
disconnect() {
window.onbeforeunload = null;
}
allowSubmit(_event) {
window.removeEventListener("popstate", this.confirmNavigation);
window.onbeforeunload = null;
}
confirmNavigation(_event) {
return false;
}
confirmTurboNavigation(event) {
if (!confirm(this._message)) {
event.preventDefault();
}
}
}
ConfirmNavigationController.values = { message: String };