简体   繁体   English

如何在 Flutter Web 中禁用默认浏览器快捷方式?

[英]How do I disable Default Browser Shortcuts in Flutter Web?

Problem问题

If I implement shortcuts for CTRL + + and CTRL + - in my Flutter web app, the browser will still zoom by default .如果我在我的 Flutter web 应用程序中实现CTRL + +CTRL + -的快捷方式,浏览器仍将默认缩放 I want to prevent the browser from doing so when I override the shorcuts.当我覆盖快捷方式时,我想阻止浏览器这样做。

Use case用例

When I have my custom shortcut behavior (using Shortcuts eg), I do not want the browser to still respond to it, but there is no way to prevent the default action in Flutter itself.当我有我的自定义快捷方式行为(例如使用Shortcuts )时,我不希望浏览器仍然响应它,但是没有办法阻止 Flutter 本身的默认操作。

Another example is CTRL + D , which creates a bookmark in Firefox.另一个例子是CTRL + D ,它在 Firefox 中创建一个书签。 I want to use the shortcut for duplication in my Flutter web app.我想在我的 Flutter web 应用程序中使用复制快捷方式。


How do I prevent the defaults?如何防止默认值?

You can prevent the default browser actions directly in HTML using JS.您可以使用 JS 在 HTML 中直接阻止默认浏览器操作。 Flutter has not implemented a way to trigger this using the framework (and I doubt they will because it is web-specific). Flutter 尚未实现使用框架触发此操作的方法(我怀疑他们会这样做,因为它是特定于 Web 的)。


If you wanted to, you could also do this using Dart code instead, using the dart:html library.如果您愿意,您也可以使用 Dart 代码,使用dart:html库来执行此操作。 However, it is most convenient to directly include the following JavaScript code in the index.html of your Flutter web app (in the <body> tag): However, it is most convenient to directly include the following JavaScript code in the index.html of your Flutter web app (in the <body> tag):

<script>
  // This prevents default browser actions on key combinations.
  // See https://stackoverflow.com/a/67039463/6509751.
  window.addEventListener('keydown', function(e) {
    if (event.target == document.body) {
      // Prevents going back to the previous tab.
      if (event.key == 'Backspace') {
        event.preventDefault();
      }
    }
  
    if (event.metaKey || event.ctrlKey) {
      switch (event.key) {
        case '=': // Prevent zooming in.
        case '-': // Prevent zooming out.
        case 'd': // Prevent bookmark on Firefox e.g.
        case 'g': // Prevent open find on Firefox e.g.
        case 'z': // Prevent restoring tab on Safari.
          event.preventDefault();
          break;
      }
    }
  });
</script>

As you can see, I added a few examples, like CTRL + D et al.如您所见,我添加了一些示例,例如CTRL + D等。 inspired by Rive.灵感来自 Rive。

Additionally, I added a snippet that prevents going back to the previous tab on pressing backspace.此外,我添加了一个片段,可防止在按退格键时返回上一个选项卡。 The use case for this is if you want to use backspace as a shortcut for deletion outside of text input .用例是如果您想使用退格键作为在文本输入之外删除的快捷方式。

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

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