I want call windows.onbeforeunload in an mvc application. I am using same laout page for all the views. I want to execute one logic on the tab/browser close. I tried adding in the layout page, but it gets called each time when moving to different view which uses same layout page. Can some one please suggest the proper place to call the function?
Loading

Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 4, 2024, 10:20 AM EDT
To handle the window.onbeforeunload event in an MVC application without it triggering on every view change, you can use a combination of JavaScript and conditional logic to ensure it only runs when the user is actually closing the tab or browser. Here’s a suggested approach:
Add a flag to track navigation within the application:
Use JavaScript to set a flag when navigating within the application.
Reset the flag when the page is fully loaded.
Modify the window.onbeforeunload event:
Check the flag to determine if the event should be triggered.
My MVC Application var isInternalNavigation = false; // Set the flag when navigating within the application document.addEventListener('click', function (event) { if (event.target.tagName === 'A' && event.target.href.startsWith(window.location.origin)) { isInternalNavigation = true; } }); // Reset the flag when the page is fully loaded window.addEventListener('load', function () { isInternalNavigation = false; }); // Handle the onbeforeunload event window.onbeforeunload = function (event) { if (!isInternalNavigation) { // Your logic here return 'Are you sure you want to leave?'; } }; @RenderBody()Ensure internal navigation is tracked correctly:
The above script sets isInternalNavigation to true when an internal link is clicked.
It resets the flag to false when the page is fully loaded.
This way, the window.onbeforeunload event will only trigger when the user is actually closing the tab or browser, not when navigating between views within your application.
Thanks