Avatar of Rohit Bajaj
Rohit Bajaj
Flag for India asked on

Displaying a confirmation box inside javascript unload event

HI,
I have added an unload event to my page like :
window.addEventListener('unload', function(event) {
    if(cancel === false) {
        return "Changes you made will not be saved";
    }
});

Bascially when unloading happens i want a confirmation dialog to appear
with two buttons ok and cancel. And if user presses ok then proceed with the normal flow otherwise stop closing of the current window.

But somwhow the dialog itself is not appearing. Many places say that
you cannot have confirmation dialog from inside an unload event so i tried returning a string but that also didnt work.
I am making it work in chrome .

Thanks
JavaScriptWeb Development

Avatar of undefined
Last Comment
Rohit Bajaj

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Rohit Bajaj

ASKER
This does not work. Setting breakpoints the code is not reachable!! This is happening most likely because my web application is opened inside an iframe and close button is not part of my application. So although window.addEventListener('unload' this was getting executed but problem was with confirmation dialog. The code mentioned by you is ignored.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck