Unload Event for NodeJS SPA

Hi.
I have a simple NodeJS app with a layout and two content pages - home and chat. I have links on the page to switch between the two content pages. Everything works fine.
What I need to do is if the user in chat page, and they decide the redirect away from the page, show them a confirmation prompt. I added below JS code for the same:

window.addEventListener('beforeunload', function (e) {
    if (location.pathname.startsWith('/chat')) {
        e.preventDefault();
        e.returnValue = 'chat might be lost';
    }
});

If I try to close the browser or tab, this works fine.
But if I click the home link, or press browser back or forward, it fails. Event is not invoked, so there is no prompt and the user is redirected.

I have done similar setup on ASP & PHP server model project before, and this event fires correctly on both link clicks or browser navigation button clicks. But on this NodeJS app, doesn’t seem to be working.
Please help.

Community Page
Last updated: