Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to get a notification when an element is added to the page using JavaScript?
Next article icon

How to display warning before leaving the web page with unsaved changes using JavaScript ?

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To display a warning before leaving a web page with unsaved changes, you can use the beforeunload event in JavaScript.

Syntax:

// Event listener for the 'beforeunload' event
window.addEventListener('beforeunload', function (e) {
// Check if any of the input fields are filled
if (fname !== '' || lname !== '' || subject !== '') {
// Cancel the event and show alert that
// the unsaved changes would be lost
e.preventDefault();
e.returnValue = '';
}
});

Approach

  • The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources. The result of this event depends on the user’s selection to proceed or cancel the action. This event can be used to check whether the user has left a form incomplete or unsaved by following this approach. 
  • Every form field on the page is used to update its respective variable by calling a function. These variables are checked whenever beforeunload is fired, thereby checking if the user is trying to leave the page without saving changes. It would not alert the user if the form is empty as the user has not started filling the form.

Example: This example displays a warning before leaving the web page with unsaved changes using JavaScript.

HTML
<!DOCTYPE html> <html> <body>     <h1 style="color: green;">         GeeksforGeeks     </h1>      <p>         The page will notify if the user has         started filling the form and tries         to navigate away from it.     </p>      <div class="container">         <h2>A Demo Contact Form</h2>         <form action="#">             <label>First Name</label>              <!-- Create all the input boxes and             assign their respective functions             to update the content in a variable -->             <input type="text"                     id="fname"                     name="firstname"                     onchange="updateFname()">              <label>Last Name</label>             <input type="text"                     id="lname"                     name="lastname"                     onchange="updateLname()">              <label>Subject</label>             <textarea id="subject"                        name="subject"                        style="height:100px"                        onchange="updateSubject()">             </textarea>              <button class="submit-btn"                      onclick="return false;">                 Submit             </button>         </form>     </div> </body> </html> 
CSS
.container {     border: 2px dotted;     width: 60%;     border-radius: 5px;     padding: 10px; }  input, textarea {     width: 90%;     padding: 10px;     margin: 10px; }  .submit-btn {     background-color: green;     color: white;     padding: 10px; } 
JavaScript
// Variables to store the input text let fname = ''; let lname = ''; let subject = '';  // Functions to update the input text updateFname = () => {     fname = document         .getElementById('fname').value; }  updateLname = () => {     lname = document         .getElementById('lname').value; }  updateSubject = () => {     subject = document         .getElementById('subject').value; }  // Event listener for the  // 'beforeunload' event window.addEventListener('beforeunload',     function (e) {          // Check if any of the input         // fields are filled         if (fname !== '' ||             lname !== '' ||             subject !== '') {              // Cancel the event and             // show alert that the unsaved             // changes would be lost             e.preventDefault();             e.returnValue = '';         }     }); 

Output:




Next Article
How to get a notification when an element is added to the page using JavaScript?
author
prasannareddyisireddy
Improve
Article Tags :
  • CSS
  • HTML
  • JavaScript
  • Technical Scripter
  • Web Technologies
  • JavaScript-Questions
  • Technical Scripter 2020

Similar Reads

  • How to Display Changed Browser URL Without Reloading Through alert using JavaScript ?
    To change the URL in the browser without loading the new page, we can use history.pushState() method and replaceState() method from JavaScript. To display the browser-URL before changing the URL we will use window.location.href in the alert() function and will use again after changing the browsers-U
    1 min read
  • How to close window using JavaScript which is opened by the user with a URL ?
    JavaScript does not allow one to close a window opened by the user, using the window.close() method due to security issues. However, we can close a window by using a workaround. The approach to be followed is by opening the current URL using JavaScript so that it could be closed with a script. Synta
    2 min read
  • How to remove hash from window.location with JavaScript without page refresh ?
    The replaceState() method is used to modify the current history entry, replacing it with the state objects, title, and URL passed in the method parameters. This method is useful when you want to update the state object or URL of the current history entry in response to some user action. To remove th
    1 min read
  • How to display error without alert box using JavaScript ?
    JavaScript errors are displayed using alert boxes, which can interrupt user experience and feel outdated. But Now, there are many alternatives to alert boxes for displaying error messages in a more user-friendly way. This article covers different methods to display errors dynamically without using a
    3 min read
  • How to get a notification when an element is added to the page using JavaScript?
    To show a notification when an element is added to the page we can use the to createElement() method to create an element list with the specified name. Detect element addition dynamically in the DOM using JavaScript. Trigger an alert to notify users upon appending new elements to the page. ApproachT
    2 min read
  • How to print a web page using JavaScript ?
    Javascript is the world most popular lightweight, cross-platform, interpreted compiled programming language, along with a scripting language for web. It facilitates the dynamic functionality that helps to make the interactive website. As all the Morden browsers use the Javascript & is a client-s
    2 min read
  • How to change a button text on click using localStorage in Javascript ?
    In this article, we will learn how to change a button text using Javascript localStorage when we click on the button achieved by adding HTML onclick event listener. Approach: HTML DOM Window localStorage allows us to store key-value pairs in our browser using an object. The name of the key should be
    3 min read
  • How to modify URL without reloading the page using JavaScript ?
    In this article, we are going to see how to modify URL without reloading the page using JavaScript Below are the methods to modify the URL without reloading the page using JavaScript: Table of Content Replacing the current state with replaceState() MethodAdding a new state with pushState() MethodMet
    3 min read
  • How to Redirect to Another Webpage using JavaScript?
    JavaScript can redirects the users from current page to another webpage (different URL) with and without requiring any manual action (like clicking a link). To redirect to another weboage in JavaScript we need to manipulate the window.location object and it will allow us to navigate programmatically
    2 min read
  • How to check whether the background image is loaded or not using JavaScript ?
    In this article, we will check whether the background image is loaded or not using JavaScript. In JavaScript, onload event is used to check whether a window is loaded or not. Similarly, we can use that event to check whether a particular element has loaded or not. There are two ways in which we can
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences