0

I know this isn't an hard answer to find but i want to disable page refresh in browser. I am developing an exam application where when users start test, it will open up in a new window. but i don't want users to refresh this test page.

I could do this using below JavaScript code:

document.onkeydown = function (e) {
    var key;
    if (window.event) {
        key = event.keyCode
    } else {
        var unicode = e.keyCode ? e.keyCode : e.charCode
        key = unicode
    }
    switch (key) { //event.keyCode
        case 116:
            //F5 button
            alert("11");
            event.returnValue = false;
            key = 0; //event.keyCode = 0;
            return false;
        case 82:
            //R button
            if (event.ctrlKey) {
                alert("11");
                event.returnValue = false;
                key = 0; //event.keyCode = 0;
                return false;
            }
    }
}

but when users go to the location/url bar and focus it and hit f5 button, page refreshes. Not just f5 but for shift+f5, browser shows same behaviour. how to avoid this?

Please help.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
user3395788
  • 93
  • 2
  • 9

2 Answers2

1

Something like this should get you closer to your goal.

window.onload = function () {
    document.onkeydown = function (e) {
        return (e.which || e.keyCode) != 116;
    };
}
abbotto
  • 4,259
  • 2
  • 21
  • 20
0

The problem is that what you are trying to do is fundamentally dangerous as allowing web pages too much control over browser behavior can easily be abused by unscrupulous or buggy websites.

Things like closing pages, refreshing pages, etc cannot be blocked. Even if you block the keyboard shortcut people can always just navigate to the URL again.

A better question would be to say why you don't want them to refresh and fix that. For example if its because you have a javascript countdown for the test time then that can be fixed by recording the time they started in the database and when they refresh resuming the countdown from the correct point.

Tim B
  • 40,716
  • 16
  • 83
  • 128