Javascript DOM onbeforeunload Event via addEventListener() method

Introduction

In JavaScript, using the addEventListener() method:

object.addEventListener("beforeunload",
       myScript);

This example uses the addEventListener() method to attach a "beforeunload" event to the window object.

Close this window, press F5 or click on the link below to invoke the beforeunload event.

View in separate window

<!DOCTYPE html>
<html>
<body>
<a href="https://www.java2s.com">Click here to go to java2s.com</a>
<script>
window.addEventListener("beforeunload", function(event) {
  event.returnValue = "Write something clever here..";
});/*from www.j a v a2 s .  c o  m*/
</script>

</body>
</html>
Bubbles: No
Cancelable: Yes
Event type: UiEvent if generated from a user interface, Event otherwise
Supported HTML tags: <body>



PreviousNext

Related