0

I want to trigger the in-browser message of "Leave Site?" before leaving a specific form on my site (exactly how StackOverflow does it).

The form is at /posts/new (or /posts/xxx/edit).

Current problems:

  • Once this page is loaded, the message works but then also shows when trying to leave any page. How can I restrict this to only this page?
  • The alert is triggered via turbo, but it's not the same "Leave Site?" browser pop-up

I want it to look like this for both the window event and turbo event: Leave Site? Pop-up

This is how it currently looks when trigger via Turbo: Leave Site? Pop-up via Turbo

Here is my current JS code:

// javascript/controllers/unsaved_changes_controller.js
import { Controller } from "@hotwired/stimulus"

const alert_message = "Leave site? Changes you made may not be saved."

export default class extends Controller {

  connect() {
    window.addEventListener("beforeunload", (event) => {
      leavingPage(event);
    });  
    document.addEventListener('turbo:before-visit', (event) => {
      leavingPage(event);
    });
  }
  
}

function leavingPage(event) {
  console.log("leavingPage")
  if (event.type == "turbo:before-visit") {
    if (!window.confirm(alert_message)) { 
      event.preventDefault()
    }
  } else {
    event.returnValue = alert_message;
    return event.returnValue;
  }
}

And my view:

<form ... data-controller="unsaved-changes">
Kobius
  • 674
  • 7
  • 28

1 Answers1

1

How can I restrict this to only this page?

  • The simplest way to do this would be just to not add the data-controller="unsaved-changes" when you do not want to trigger the warning.
  • Alternatively you can read the event's detail.url to check what URL is being navigated to https://turbo.hotwired.dev/reference/events OR read the current URL via window.location.

Use the same "Leave Site?" browser pop-up

This special alert / pop-up cannot be triggered in any other way except for the actual beforeunload event usage.

Even using this has some caveats and scenarios where it will not work - see https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#usage_notes

LB Ben Johnston
  • 4,751
  • 13
  • 29