'How to fix this dialog spam on my page? - JavaScript [duplicate]

I wanted to make a function that asks you if you really wanna leave the page when you try to leave, but where ever I press on my page it asks me this instead only when I try to leave, how do I fix it

The code:

document.addEventListener("DOMContentLoaded", function () {
    //Dialog
    document.addEventListener("click", function leave(){
        if(confirm("You sure you wanna leave this page?")){}
        else{
            alert("Staying on page"+ " " + document.title +".");
            event.preventDefault();
        } 
    });


Solution 1:[1]

You can use this code instead :-

window.onbeforeunload = function(e) {
  return "Do you want to exit this page?";
};

Note :- This would not work until the user interact with the web page

Solution 2:[2]

You are binding the leave function to the click event, you should bind it to beforeunload event.

Fixed code:

document.addEventListener("DOMContentLoaded", function() {
  //Dialog
  document.addEventListener("beforeunload", function leave(event) {
    if (confirm("You sure you wanna leave this page?")) {} // do nothing
    else {
      alert("Staying on page" + " " + document.title + ".");
      event.preventDefault();
    }
  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mplungjan
Solution 2 mplungjan