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.