JSFiddle - React, Tailwind, and code Playground

by Julien Etienne

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Unload Confirmation</title>
</head>
<body>

    <script>
        let pendingTask = false;

        // Simulate a pending task
        function simulateTask() {
            pendingTask = true;
            setTimeout(() => {
                pendingTask = false;
            }, 3000); // Simulating a 3-second task
        }

        // Check if there are pending tasks before unloading
        window.addEventListener('beforeunload', function (e) {
            if (pendingTask) {
                const confirmationMessage = 'You have pending tasks. Are you sure you want to leave?';
                e.returnValue = confirmationMessage; // Standard way of displaying a prompt
                return confirmationMessage; // Fallback for older browsers
            }
        });
    </script>

    <button onclick="simulateTask()">Start Task</button>

</body>
</html>