Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the behavior of the F5 button

I want to change the behavior of the F5 refresh button of the browser for example when user click on F5 the page will not be refreshed and some alert will appear ,Currently I've tried with this code(which I find in after search in the forum) but it's not working,Im having reference to jquery cdn.any idea what is missing?

function disableF5(e) {
debugger;
    alert("clicked");
    if (e.which === 116 || e.keyCode === 116) {

        e.preventDefault();
        alert("clicked");
    }
}

$(function() {

    $(document).on("keydown", disableF5);
});

I also tried like following which is not working either ,any idea what I miss here?

 document.addEventListener('keydown', function(e) {
     debugger;
     if(e.which === 116 || e.keyCode === 116) {
         alert("1234");
         e.preventDefault();
     }

Edit

also tried with the following and still its not stop in the debugger and I dont see the alert (all the example which I provide stops in the document ready)

function disableF5(e) {
    if ((e.which || e.keyCode) === 116 || (e.which || e.keyCode) === 82) {
        debugger;
        alert("test")
        e.preventDefault();
    }}

    $(document).ready(function() {
        $(document).on("keydown", disableF5);
    });
like image 957
John Jerrby Avatar asked Jan 10 '23 14:01

John Jerrby


1 Answers

Try using this method that uses JavaScript and Jquery:

function disableF5(e) {
  if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82)
  e.preventDefault();
};

$(document).ready(function(){
  $(document).on("keydown", disableF5);
});

Note:
I would not recommend preventing the page from refreshing however, I would recommend using a popup warning users about navigating away from the page eg:

window.onbeforeunload = function() {
    return "Are you sure you want to leave?";
}

source
I hope I helped

like image 109
Oliver Avatar answered Jan 12 '23 08:01

Oliver