JavaScript 如何在离开网页前显示未保存更改的警告

JavaScript 如何在离开网页前显示未保存更改的警告

在这篇文章中,我们将学习如何使用JavaScript和“beforeunload”事件监听器,在离开网页前显示未保存更改的警告信息。

在开发网页应用程序或任何类型的表单时,提供一个警告信息让用户知道他们将要离开具有未保存更改的页面变得必要。这可以防止意外数据丢失并改善用户体验。让我们通过一些示例来了解如何实现这一功能:

示例1

在这个示例中,我们将有一个包含多个输入元素的表单,并在窗口对象上添加一个“beforeunload”事件监听器来检测用户是否要离开页面。在事件监听器的回调函数中,我们将检查用户在表单中是否有任何已保存的更改。如果有,我们将显示一个提示框,提示存在未保存的更改;否则,用户将继续离开页面。

文件名:index.html

<html lang="en">
   <head>
      <title>How to display warning before leaving the web page with unsaved changes using JavaScript?</title>

      <style>
      #myForm {
         display: flex;
         flex-direction: column;
         width: 300px;
         gap: 10px;
      }
      </style>
   </head>
   <body>
      <form id="myForm">
         <label for="name">Name:</label>
         <input type="text" id="name" name="name" />
         <label for="email">Email:</label>
         <input type="text" id="email" name="email" />
         <label for="subject">Subject:</label>
         <input type="text" id="subject" name="subject" />
         <input type="submit" value="Submit" />
      </form>

   <button id="refresh">Refresh the page!</button>

   <script>
      const form = document.getElementById('myForm');
      const name = document.getElementById('name');
      const email = document.getElementById('email');
      const subject = document.getElementById('subject');
      const submitBtn = document.querySelector('input[type="submit"]');
      const refreshBtn = document.getElementById('refresh');

      refreshBtn.addEventListener('click', e => {
         e.preventDefault();
         window.location.reload();
      })

      const initialFormState = {
         name: name.value,
         email: email.value,
         subject: subject.value
      };

      submitBtn.addEventListener('click', e => {
         e.preventDefault();
      })

      window.addEventListener('beforeunload', e => {
         const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
         }

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            e.preventDefault();
            e.returnValue = '';
         }
      })
   </script>
   </body>
</html>

示例2

在这个示例中,我们将遵循上述的代码结构,并使用3种不同的方法,在离开网页之前显示一个警告消息,使用onbeforeunload、pagehide和unload事件。

文件名:index.html

<html lang="en">
<head>
   <title>How to display warning before leaving the web page with unsaved changes using JavaScript?</title>

   <style>
      #myForm {
         display: flex;
         flex-direction: column;
         width: 300px;
         gap: 10px;
      }
   </style>
</head>
<body>
   <form id="myForm">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" />
      <label for="email">Email:</label>
      <input type="text" id="email" name="email" />
      <label for="subject">Subject:</label>
      <input type="text" id="subject" name="subject" />
      <input type="submit" value="Submit" />
   </form>

   <button id="refresh">Refresh the page!</button>

   <script>
      const form = document.getElementById('myForm');
      const name = document.getElementById('name');
      const email = document.getElementById('email');
      const subject = document.getElementById('subject');
      const submitBtn = document.querySelector('input[type="submit"]');
      const refreshBtn = document.getElementById('refresh');

      refreshBtn.addEventListener('click', e => {
         e.preventDefault();
         window.location.reload();
      })

      const initialFormState = {
         name: name.value,
         email: email.value,
         subject: subject.value
      };

      submitBtn.addEventListener('click', e => {
         e.preventDefault();
      })

      // Example 1: Using onbeforeunload Property
      window.onbeforeunload = function() {
         const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
         };

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            return 'You have unsaved changes. Are you sure you want to leave this page?';
         }
      };

      // Example 2: Using pagehide event
         window.addEventListener('pagehide', function(e) {
            const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
            };

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave this page?';
            (e || window.event).returnValue = confirmationMessage;
            return confirmationMessage;
            }
         });

      // Example 3: Using onunload property
      window.onunload = function() {
         const currentFormState = {
            name: name.value,
            email: email.value,
            subject: subject.value
         };

         if (JSON.stringify(initialFormState) !== JSON.stringify(currentFormState)) {
            // Perform any necessary cleanup actions
         }
      };
   </script>
</body>
</html>

结论

总之,使用JavaScript在离开含有未保存更改的网页前实现警告信息对于提供更好的用户体验和防止意外数据丢失至关重要。通过按照本文提供的示例HTML结构和JavaScript代码,我们学会了如何轻松地将此功能集成到我们的网页应用程序或表单中。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程