简体   繁体   English

区分F5或打开浏览器

[英]Distinguish F5 or Open for Browser

Is it possible to distinguish F5 or Open (click on link, paste URL in empty page or new tab, etc.) for Browser? 是否可以为浏览器区分F5或“打开”(单击链接,将URL粘贴到空白页或新标签中,等等)?

Why? 为什么? Because I'd like to improve ergonomics of user interface. 因为我想改善用户界面的人体工程学。 In my application some costly computations used to render a page. 在我的应用程序中,一些昂贵的计算用于呈现页面。 So page is cached and there is additional button on the page "Recalculate". 因此页面被缓存,页面“重新计算”上还有其他按钮。

I don't like having additional "Recalculate" button when there are exactly the same standard "F5" button. 当有完全相同的标准“ F5”按钮时,我不喜欢额外的“重新计算”按钮。

I control both Server & Client JS, is there any way to be notified about "F5" event? 我同时控制服务器和客户端JS,是否有任何方法可以通知“ F5”事件?

It is important to detect all "F5" events and not miss it. 重要的是要检测所有“ F5”事件,不要错过它。 But it is ok to have sometimes (sometimes but not frequently) additional false "F5" events - when Open Page has been mistakenly detected as "F5". 但是,有时(有时但不经常)有其他错误的“ F5”事件是可以的-当打开页面被错误地检测为“ F5”时。

In your case, using sessionStorage sounds like your best option. 就您而言,使用sessionStorage听起来是您的最佳选择。

Something like: 就像是:

var calculatedValues = (function() {
  var savedValues = sessionStorage.getItem("values");
  if (!savedValues) {
    // Do calculations
    var values = {
      result: 10
    };

    savedValues = JSON.stringify(values);
    sessionStorage.setItem("values", savedValues);
  }
  return JSON.parse(savedValues);
}());

sessionStorage should be unique for every window -- going to to the page under a different window will see no values and recalculate, but pressing F5 won't. sessionStorage对于每个窗口都应该是唯一的-转到不同窗口下的页面将看不到任何值并重新计算,但是按F5则不会。

Some browsers will copy session values from one window to another when using Open in new tab on a link, but it sounds like that won't be an issue in this case. 当使用链接上的“ Open in new tab时,某些浏览器会将会话值从一个窗口复制到另一个窗口,但是听起来在这种情况下这不是问题。

Take a look on the keydown javascript event: 看看keydown javascript事件:

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/keydown https://developer.mozilla.org/zh-CN/docs/Web/Reference/Events/keydown

You can then use its key property to check for F5, and block the browser's reload with event.preventDefault 然后,您可以使用其key属性检查F5,并使用event.preventDefault阻止浏览器重新加载。

document.body.addEventListener("keydown", function(event) {
    if (event.key == "F5") {
        console.log("F5 Pressed!");
        //do your stuff here
        event.preventDefault();
    }
});

Fiddle: http://jsfiddle.net/ANC7e/ 小提琴: http//jsfiddle.net/ANC7e/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM