To prevent data loss, do you want to create the following warning popup (alert) before a user of your web page attempts to close, reload, or leave the page via the “back” button?

You can do this in a simple step: just copy and paste the following JavaScript code snippet between the <head> ... </head>
tags.
<script> window.addEventListener('beforeunload', function (e) { // Cancel the event e.preventDefault(); // Chrome requires returnValue to be set e.returnValue = ''; }); window.onbeforeunload=function(){return "Navigating away will lose the changes you've made to your code."}; </script>
By defining the window.onbeforeunload
attribute, you tell the browsers (Firefox, Chrome, Internet Explorer, Safari) that there may be some data loss when users close the window.
However, this must be true—you need to have a form, etc. where data actually changed since the user visited the web page. Modern browsers are smart about this feature to prevent missuse.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.