Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

javascript - Disable F5 key in Safari 4

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...