Pramod Badgujar
Pramod Badgujar

Reputation: 95

Prevent user from refreshing the page

I want to prevent the user from refreshing the page, How to do this? I have been using e.preventDefault method but it`s not running properly.

Upvotes: 5

Views: 20577

Answers (5)

Aswin Prasad
Aswin Prasad

Reputation: 9

I have two different solutions for this , both are based on what operation you do i will explain with form submission:

  1. using e.preventDefault();
  2. using return false;

HTML

<form id="myForm">.....</form>

JS

document.getElementById("myForm").addEventListener("submit", (e) => {
    e.preventDefault();
    ...
});

(or)

HTML

<form id="myForm" onsubmit="return submitForm()">.....</form>

JS

function submitForm() {
    ...
    return false;
}

But the 2nd Option works good for the Form Processing..!

Thank You.

Upvotes: 0

Wenfang Du
Wenfang Du

Reputation: 11337

The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user.

window.addEventListener('beforeunload', evt => {
  // Recommended
  evt.preventDefault()
  // Included for legacy support, e.g. Chrome/Edge < 119
  evt.returnValue = true
})

Reference: Window: beforeunload event

Upvotes: 5

EzWinz
EzWinz

Reputation: 45

It is not advised, but if you want to completely prevent the user from refreshing the page in any way possible you can use:

setInterval(function(){
  window.location.reload();
  window.stop();
},100)

Not only will it prevent refreshing, but it will also prevent navigation.

Upvotes: 1

RPichioli
RPichioli

Reputation: 3345

Try something like:

<script type="text/javascript">
    // Callback
    window.onbeforeunload = function(e) {
        // Turning off the event
        e.preventDefault();
    }
</script>

Some basic explanations about these features

preventDefault: http://www.w3schools.com/jsref/event_preventdefault.asp

beforeunload: http://www.w3schools.com/jsref/event_onbeforeunload.asp

Upvotes: 1

Mannan Bahelim
Mannan Bahelim

Reputation: 1355

you can use the window.onbeforeunload even.

window.onbeforeunload = function() {
            return "you can not refresh the page";
        }

Upvotes: 3

Related Questions