JavaScript onbeforeunload Event

You are Here:

JavaScript onbeforeunload Event

The onbeforeunload event occurs when the document is about to be unloaded.

This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.

The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like "Changes you made may not be saved.". This message cannot be overwritten.

Note: Some browsers allow you to customize the message to the user. However, this is deprecated and no longer supported in most browsers.

onbeforeunload Event as Attribute

Example

HTML Online Editor
<!DOCTYPE html> <html> <body onbeforeunload="return myFunction()"> <a href="https://wikimass.com">Wikimass.com</a> <script> function myFunction(){ // default value, cannot be modified return 'Changes you made may not be saved.'; } </script> </body> </html>

Syntax

As Attribute

<element onbeforeunload = "JavaScript">

As Property

object.onbeforeunload = function(){ // code };

Using Event Listener

window.addEventListener("beforeunload" , myScript);

onbeforeunload Event as Property

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <a href="https://wikimass.com">Wikimass.com</a> <script> var x = document.getElementsByTagName("body")[0]; function myFunction(){ // default value, cannot be modified return 'Changes you made may not be saved.'; } x.onbeforeunload = myFunction; </script> </body> </html>

Using addEventListener() Method

Note: The addEventListener() method is not supported in Internet Explorer 8 and below.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <a href="https://wikimass.com">Wikimass.com</a> <script> window.addEventListener("beforeunload", function(event) { // default value, cannot be modified event.returnValue = "Changes you made may not be saved."; }); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author