Repository: flutter
Issue: Inconsistent behavior of external requests on Flutter for web due to issue in service worker
Labels: tool,platform-web,has reproducible steps,assigned for triage,team-web,found in release: 3.24,found in release: 3.26

### Steps to reproduce

I have created a GitHub repo to showcase the issue: https://github.com/Frank3K/flutter_service_worker_bug

## Prerequisites

Ensure you have a tool installed that can run an HTTP server to serve the contents of a directory. Here, Python 3 is used as an example. Other examples can be found at https://gist.github.com/willurd/5720255.

## Reproduction steps

1. Clone the repository on https://github.com/Frank3K/flutter_service_worker_bug.
2. Install dependencies: `flutter pub get`.
3. Compile for web: `flutter build web`
    - Note that `flutter run -d chrome` is not sufficient, since service workers are empty in `run` mode.
4. Serve the output, e.g., using `python3 -m http.server 8080 -d build/web`.
5. Open the following URLs in Chrome:
    - http://this-is-a-very-long-url-thats-sooooooooooooooooooooooooooo-long.localhost:8080/
    - http://short.localhost:8080/
6. Open the network tools.
7. In each tab, press the download (FAB) button.
8. Observe that for the long URL, the request is processed by the service worker (a ⚙ is present), and for the short URL, it is not.



### Expected results

## Expected results

The expected result is that the service worker does not handle external requests.

## Cause of this discrepancy

Looking into the service worker code, we find the following code: [link](https://github.com/flutter/flutter/blob/2528fa95eb3f8e107b7e28651a61305d960eef85/packages/flutter_tools/lib/src/web/file_generators/js/flutter_service_worker.js#L87-L95):

```js
  var origin = self.location.origin;
  var key = event.request.url.substring(origin.length + 1);
  // Redirect URLs to the index.html
  if (key.indexOf('?v=') != -1) {
    key = key.split('?v=')[0];
  }
  if (event.request.url == origin || event.request.url.startsWith(origin + '/#') || key == '') {
    key = '/';
  }
```

Depending on the length of the URLs, the `substring` returns the empty string, which later on becomes `/`.

### Suggested fix

Bail out when the request is to an external URL. For example, using:

```js
  var requestURL = new URL(event.request.url);
  if (requestURL.origin !== origin) {
    return;
  }
```

### Actual results

Some external requests are processed by the service worker in Flutter for web and other requests are not, depending on the length of the application URL in combination with the request URL.

For example, given an application URL: https://www.some-website-example.com that makes the following requests:

- A GET request to https://www.some-api.com/status
- A GET request to https://www.another-api.com/items/12345

The first request will be processed (and cached) by the service worker, while the second one will not.

### Code sample

The source for an application showcasing the issue can be found over at:

https://github.com/Frank3K/flutter_service_worker_bug

### Screenshots or Video

<details open>
<summary>Screenshots / Video demonstration</summary>

Long URL: service worker handling the request:

<img width="908" alt="image" src="https://github.com/user-attachments/assets/8fd71be3-3c0f-4577-90ba-4f6ec4f14171">

Short URL: service worker not handling the request:

<img width="768" alt="image" src="https://github.com/user-attachments/assets/80d1b7b7-7551-44f9-b484-9c9450ba42e5">


</details>


### Logs

<details open><summary>Logs</summary>

```console
[Paste your logs here]
```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.24.3, on macOS 14.6.1 23G93 darwin-x64, locale en-NL)
    • Flutter version 3.24.3 on channel stable at /Users/<redacted>/.asdf/installs/flutter/3.24.3
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 2663184aa7 (9 days ago), 2024-09-11 16:27:48 -0500
    • Engine revision 36335019a8
    • Dart version 3.5.3
    • DevTools version 2.37.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/<redacted>/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • ANDROID_HOME = /Users/<redacted>/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11572160)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 16.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 16A242d
    ! iOS 18.0 Simulator not installed; this may be necessary for iOS and macOS development.
      To download and install the platform, open Xcode, select Xcode > Settings > Platforms,
      and click the GET button for the required platform.

      For more information, please visit:
        https://developer.apple.com/documentation/xcode/installing-additional-simulator-runtimes
    ! CocoaPods 1.12.1 out of date (1.13.0 is recommended).
        CocoaPods is a package manager for iOS or macOS platform code.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/to/platform-plugins
      To update CocoaPods, see https://guides.cocoapods.org/using/getting-started.html#updating-cocoapods

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11572160)

[✓] VS Code (version 1.93.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.96.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-x64     • macOS 14.6.1 23G93 darwin-x64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 128.0.6613.138

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.
```

</details>