Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Know status of windows.beforeunload event by user

I am using windows.beforeunload event to prompt user whether they would like to unsaved changes or not.

Inside windows.beforeunload event, I want to know status whether user clicked on "Leave" button or "Cancel" button (In Chrome). Is it possible? If not then any alternate solution?

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Per MDN beforeunload

This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.

The above implies that the event is cancelable, but...

According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.

And even then, if you are indeed doing that...

To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.

Proper Use Case

However, unlike the unload event, there is a legitimate use case for the beforeunload event: the scenario where the user has entered unsaved data that will be lost if the page is unloaded.

It is recommended that developers listen for beforeunload only in this scenario, and only when they actually have unsaved changes, so as to minimize the effect on performance. See the Examples section below for an example of this.

See the Page Lifecycle API guide for more information about the problems associated with the beforeunload event.

Example

In this example a page listens for changes to a text input. If the element contains a value, it adds a listener for beforeunload. If the element is empty, it removes the listener:

const beforeUnloadListener = (event) => {
  event.preventDefault();
  return event.returnValue = "Are you sure you want to exit?";
};

const nameInput = document.querySelector("#name");

nameInput.addEventListener("input", (event) => {
  if (event.target.value !== "") {
    addEventListener("beforeunload", beforeUnloadListener, {capture: true});
  } else {
    removeEventListener("beforeunload", beforeUnloadListener, {capture: true});
  }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!