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 MakwanaPosted Sep 4, 2024, 2:20 PM
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.
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