How do I load a specific url on refresh?

2019-09-10 03:57发布

问题:

Let's say that someone decides to press F5 or the browser's reload button. Is that possible to open a specific url in the same tab?

回答1:

Like posted in comment, if you display prompt, this is possible using following ugly hack:

var a,b;
window.onbeforeunload = function (e) {
    if (b) return;
    a = setTimeout(function () {
        b = true;
        window.location.href = "//test.com";
    }, 500);
    return "Now you will be redirected to new page if choosing to stay there...";
}
window.onunload = function () {
    clearTimeout(a);
}



回答2:

Use This

// To check if someone pressed f5 or leaving the page

window.onbeforeunload = function () {

    //for changing the url

    var newUrl = "http://www.someurl.com";
    window.location.href = newUrl;
}; 


回答3:

As noted in this Stack Overflow answer, the ShortCut library is designed to handle keyboard button events, including F-keys and arrow-buttons etc.

However, I must say that the idea of redirecting people to another page or site when they think they are refreshing the page is not only bad practice, but open to abuse.