Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have written the following Javascript code to catch F5 key press and prevent the user from refreshing:

(I understand this is not a good idea but I am stuck with this whether any one likes it or not. Also the question I ask pertains to why the script below does not work with Safari 4 but works for other browsers.)

var fn = function (e)
{

    if (!e)
        var e = window.event;

    var keycode = e.keyCode;
    if (e.which)
        keycode = e.which;

    var src = e.srcElement;
    if (e.target)
        src = e.target;    

    // 116 = F5
    if (116 == keycode)
    {
        // Firefox and other non IE browsers
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        // Internet Explorer
        else if (e.keyCode)
        {
            e.keyCode = 0;
            e.returnValue = false;
            e.cancelBubble = true;
        }

        return false;
    }
}

// Assign function to onkeydown event
document.onkeydown = fn;

The above code works perfectly for IE 6,7 and 8, from Firefox 2.0 onwards and also in Chrome.

However it does not work for Safari 4 for windows. Pressing the F5 key refreshes the document. The funny thing is that in Safari the code gets inside the if (e.preventDefault) part above but for some reason its not preventing the default action i.e. refreshing the page.

Is this a bug with Safari 4 or is there some Safari specific code I need to write?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
723 views
Welcome To Ask or Share your Answers For Others

1 Answer

Never try anything that hinders a user's normal action with a browser. Even if you do this using javascript he can disable the script and then continue the page refresh.

If you need to prevent the action made on a refresh then handle it in server side.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...