How can a PHP developer enforce a confirmation prompt when a user tries to leave a page with input fields?

When a user tries to leave a page with input fields without saving their changes, it can lead to data loss. To prevent this, a PHP developer can use JavaScript to display a confirmation prompt before the user navigates away from the page. By detecting changes in the input fields and triggering the prompt accordingly, the developer can ensure that the user is aware of unsaved changes and can choose to stay on the page to save them.

<script>
    window.addEventListener('beforeunload', function (e) {
        if (document.getElementById('inputField').value !== '') {
            e.preventDefault();
            e.returnValue = '';
        }
    });
</script>