There's lots of questions on how to raise a dialog before a user leaves, and how to detect if the user decided not to leave.
javascript before leaving the page
Detecting whether user stayed after prompting onBeforeUnload
What if I want to do an action only if the user confirms that he wants to leave.
But I don't want to run action() if the user cancels the leave dialog and ends up staying on the page.
How can I detect confirm for onbeforeunload
JavaScript Dialog?