Any way to prevent user from closing tab (or showing a warning before they close it) from within Forms?

I've tried various solutions none of which seem to work in Google Chrome e.g.:

function closedWin() {
    confirm("close?");
    return false;
}

if (window.addEventListener) {
    window.addEventListener("close", closedWin, false);
}

window.onclose = closedWin;

I've also tried a few using onBeforeUnload however these do not seem to work. What I'm really missing is a beforeClose() event in Vue - as I really want to run a PnP update to the list item, even when it is not being saved - so far I can do this by modifying my close buttons, but I can't seem to be able to run it when the user closes the tab by clicking on the 'x'.

Is there anything in Forms that I can attach a handler to that will interrupt the closure of the tab?

Kind regards

Andy

Hello @abolam,

I'm not sure I understood you. Do you mean the dialog window? How do you open it?

Hi mnikitina,

I'm talking about the browser tab, not any dialog generated by the form. Appreciate this is somewhat a browser question, however my efforts to interrupt the window.close() or use window.beforeUnload do not seem to work in Google Chrome.

What I'm querying, is there something within Vue that will allow me to stop or interrupt the closure of the browser tab so that the user does not lose any data by accident. I have tried various jQuery solutions however none of those appear to work in Google Chrome.

A Vue event such as sp.beforeClose would be great, but may not exist, at least not by that name. I wonder if there is an event that can be accessed that happens before the window.close() object can process the closing of the browser tab, so I can attach some functions to it?

Hope that makes sense! Kind regards, Andy

Hello @abolam,

Ok, thank you for the details.

You can try out the code below to show the confirmation box when a user closes the tab.

window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    e.returnValue = '';
});

Thanks mnikitina, I've incorporated a similar method which also triggers a logic app to do necessary cleanup, as was finding it impossible to run any update code within the 'beforeunload' function.

Regards
Andy

Hello,

When I use this code, the user also get the confimation box when he clicks on 'Submit'. How can I prevent this?

Thank you!

Daniël

Hello @danieljr,

Try out this code:

fd.spRendered(function(vue) {
    var preventClose = function (e) {
        e.preventDefault();
        e.returnValue = '';
    }
    
    window.addEventListener('beforeunload', preventClose, true);
});

//remove event listener before submitting the form 
fd.spBeforeSave(function(spForm) {
 window.removeEventListener('beforeunload', preventClose, true);
});

This works fine with a little correction :wink:

Thank you

1 Like