如何使用 JavaScript 在離開網頁時顯示未儲存更改的警告?


在本文中,我們將學習如何使用 javascript 和“beforeunload”事件監聽器在離開網頁時顯示未儲存更改的警告訊息。

在處理任何型別的 Web 應用程式或表單時,都需要在使用者離開包含未儲存更改的頁面之前向其提供警告訊息。這可以防止意外資料丟失並改善整體使用者體驗。讓我們透過一些示例來了解如何實現這一點。

示例 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 程式碼,我們學習瞭如何輕鬆地將此功能整合到我們的 Web 應用程式或表單中。

更新於: 2023年8月3日

2K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告