2

I'm trying to add a function while closing the tab , a pop shows up with leave and cancel, i want to add a function for specific buttons like , if i click on leave button it should call a one function and if i click on cancel button it should call other function. please help me thanks in advance

window.addEventListener("beforeunload", (ev) => {  
  ev.preventDefault();
    socket.current.emit(
      "logout_patient",
       history.location.state.data.doctorAlias,
       socket.current.id,
       history.location.state.data.patientId
    );  
  return ev.returnValue = 'Are you sure you want to close?'; 
});

1 Answer 1

1
+25

You can't achieve this functionality using one event('beforeunload').

You can use the window unload event to check the user's click on the leave of popup.

window.requestAnimationFrame to check you click on cancel.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event

const onCancel = () => {
  console.log("I am the 2nd one.");
};
const onLeave = () => {
  console.log("I am the 3rd one.");

  // This loop is just to make sure that the event is fired
  for (var i = 0; i < 100000; i++) {
    console.log(event.returnValue);
  }
};

const onExit = (e) => {
  if (!e) e = window.event;
  e.returnValue = "You sure you want to leave?";
  if (e.stopPropagation) {
    e.stopPropagation();
    e.preventDefault();
  }
  console.log("I am the 1st one.");
  window.requestAnimationFrame(onCancel);
};

window.addEventListener("beforeunload", onExit, { capture: true });
window.addEventListener("unload", onLeave);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.