creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126694

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. 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 e.g.), I do not want the browser to still respond to it, but there is no way to prevent the default action in Flutter itself.

Another example is CTRL + D, which creates a bookmark in Firefox. I want to use the shortcut for duplication in my Flutter web app.


How do I prevent the defaults?

Upvotes: 1

Views: 2180

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126694

You can prevent the default browser actions directly in HTML using JS. Flutter has not implemented a way to trigger this using the framework (and I doubt they will because it is web-specific).


If you wanted to, you could also do this using Dart code instead, using the dart:html library. 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. inspired by 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.

Upvotes: 3

Related Questions