Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix this dialog spam on my page? – JavaScript

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();
        } 
    });

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading