How to implement a consent prompt when navigating away from a page without user interaction in JavaScript?

I’m developing a web application where I have an index.php page containing a form with hidden input storing request data and a submit button. I want to implement a feature where if the user attempts to navigate away from the page (e.g., by right-clicking and clicking back or reloading), a consent prompt should appear before allowing the navigation. However, I encountered an error message stating: “Blocked attempt to show a ‘beforeunload’ confirmation panel for a frame that never had a user gesture since its load.”

Here’s a simplified version of my code:

<!DOCTYPE html>
<html>
<head>
    <title>Consent Prompt</title>
</head>
<body>
    <form id="myForm" action="process.php" method="post">
        <input type="hidden" name="requestData" value="someData">
        <button type="submit">Submit</button>
    </form>
    <script>
        window.addEventListener('beforeunload', function(e) {
            e.preventDefault();
            e.returnValue = '';
        });
    </script>
</body>
</html>