捕获刷新并将页面更改为 index.html

Catch refresh and change page to index.html

我有一个问题。我想检测用户是否按下了 F5 或刷新按钮。如果是这样,我想将页面更改为 index.html。这是我的代码:

$(window).on('beforeunload',function(){

    $.mobile.changePage($(document.location.href="/index.html"),{
        transition:"slide",
        changeHash:false
    });

});

但它不起作用。有没有人有解决方案,我该如何实现?

谢谢。

直接获取键值:

$(document).keypress(function(e) {
if(e.which == 116) {
    window.location.href = '/index.html'; 
}
});

Key Reference

替代方法:

document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;

 var wasPressed = false;

 function fkey(e){
    e = e || window.event;
   if( wasPressed ) return; 

    if (e.keyCode == 116) {
         window.location.href = '/index.html'; 
        wasPressed = true;
    }else {
        alert("Window closed");
    }
 }