Open Bug 1280189 Opened 7 years ago Updated 7 months ago

[Fetch] "NetworkError when attempting to fetch resource" exception when redirecting

Categories

(Core :: DOM: Networking, defect, P3)

47 Branch
defect

Tracking

()

People

(Reporter: christian.hersevoort, Unassigned, NeedInfo)

Details

(Whiteboard: [necko-triaged])

User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36

Steps to reproduce:

I created a simple script to reproduce this issue: https://github.com/ChristianHersevoort/fetch-firefox-issue

What it does is:
1. Start a Fetch-request 
2. Open a link or redirect to another page before fetch finishes





Actual results:

Get exception "NetworkError when attempting to fetch resource" on the fetch.catch() handler


Expected results:

The canceled fetch-request should not throw an exception
We purposely abort network when the page is navigated.

Are you saying the network should continue or we should just not reject the promise?  Do you see different behavior with XHR, for example?
Flags: needinfo?(christian.hersevoort)
is the sw the right component for fetch issues?
Component: Networking: HTTP → DOM: Service Workers
Close.  Just DOM unless the site is actually using service workers.  I don't think it is in this case.
Component: DOM: Service Workers → DOM
My initial assumption was a wrong. This issue is about the timing of the exception and not specifically about fetch. 

Let me reiterate:

What it does is:
1. Start async request (fetch or XHR)
2. Open a link / Redirect to another page
3. Fetch or XHR gets rejected
3b: Page shows error to the user (because a promise was rejected)
4. New page is opened

Expected results:
1. Start async request (fetch or XHR)
2. Open a link / Redirect to another page
3. New page is opened
4. Fetch or XHR gets rejected

Note: The XHR should be rejected AFTER the new 'old' page is closed, therefore it won't show the user an error message. From a developer point of view it's not possible to distinguish between an actual error or and expected redirect.

I've updated the example (https://github.com/ChristianHersevoort/fetch-firefox-issue). For clarity I've added an jQuery ajax (XHR) example as well. The jQuery example has the same bug.
Flags: needinfo?(christian.hersevoort)
Olli, what do you think?  Are we aborting our nsILoadGroup too early?  Should we be waiting for the new document to become active?
Flags: needinfo?(bugs)
Per spec, the old document's network stuff gets stopped before the fetch of the new document _starts_.  See https://html.spec.whatwg.org/multipage/browsers.html#navigate step 11 which calls https://html.spec.whatwg.org/multipage/browsers.html#abort-a-document which in step 2 does:

  Cancel any instances of the fetch algorithm in the context of this Document, discarding any tasks queued
  for them, and discarding any further data received from the network for them.

So if there is a rejection that's going to happen here, it would happen before the fetch of the new document starts.  So the "expected results" from comment 4 are definitely wrong.  The only possibly spec-compliant things are the "what it does" list or the same thing without step 3/3b if the fetch being canceled is not supposed to reject the promise.
Oh, and at least at one point Chrome did _not_ implement the spec correctly in terms of aborting the document, as I understand.  I don't know whether they do now.

Last I checked, Safari did implement the spec correctly, but neither Safari nor WebKit nightly implements fetch, so it's hard to test this there.
I suspect this issue is causing my progressive web app to no longer work offline.

It used to in nightly on android and linux, now both don't.

I am still investigating and would appreciate any guidance in working around this.

I am basically using a pattern like
https://github.com/GoogleChrome/sw-toolbox/blob/master/lib/strategies/fastest.js

But now I get the error described here instead of a fallback to the cached file when network is down.
Can you provide a link to your site or a demo?  Does this reproduce in developer edition or beta?
Flags: needinfo?(adrian.aichner)
(In reply to Ben Kelly [:bkelly] from comment #9)
> Can you provide a link to your site or a demo?  Does this reproduce in
> developer edition or beta?

My app is fairly involved and not public.

I saw this breakage in firefox for android 48.0b10 as well.

One other thing I noticed meanwhile is that offline access does not seem to work while devtools are open in that tab. I toggle devtools off with Ctrl+Shift+I and I can you the cached app offline.

I went from the "fastest" strategy I had used before to the approach used by
https://serviceworke.rs/offline-fallback_service-worker_doc.html
with caching added in the then clause:

this.addEventListener('fetch', function(event) {
  var request = event.request;
  var url = request.url;
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (request.method == 'GET' && response && successResponses.test(response.status) &&
          request.url.match(this.registration.scope) &&
          (response.type == 'basic' || /\.(js|png|ttf|woff|woff2)/i.test(request.url) ||
           /fonts\.googleapis\.com/i.test(request.url))){
        caches.open(version).then(function(cache) {
          console.log(`put ${event.request.url} in ${version}`);
          cache.put(event.request, response.clone());
        });
      }
      return response;
    }).catch(err => {
      console.log(JSON.stringify(err, Object.getOwnPropertyNames(Error.prototype), 2));
      return caches.open(version).then(function(cache){
        console.log(`return cache.match(${url}) since fetch fails`);
        return cache.match(url);
      }).catch(err => {
        console.log(JSON.stringify(err, Object.getOwnPropertyNames(Error.prototype), 2));
      });
    })
  );
});
Flags: needinfo?(adrian.aichner)
Can you try to make a minimal test case?  Its really hard to investigate without being able to reproduce the error.  The linked SW demo works fine for me.

Also, are you creating iframes or anything?  This bug is about windows that are being closed.  Do you have such windows that are being closed?
Flags: needinfo?(adrian.aichner)
(In reply to Ben Kelly [:bkelly] from comment #11)
> Can you try to make a minimal test case?  Its really hard to investigate

I'll see whether I can file new coherent bugs, be it devtools or fetch implementation or whatever I may find.

Perhaps I find a public testcase which exposes the problem I was seeing.

> without being able to reproduce the error.  The linked SW demo works fine
> for me.

Yes, that works for me too and is what I based my reworked code on.

> 
> Also, are you creating iframes or anything?  This bug is about windows that
> are being closed.  Do you have such windows that are being closed?

No iframes, no closing windows.

I only found this bug based on the matching error type and message.
Flags: needinfo?(adrian.aichner)
I am also seeing this, and it is quite irritating. Fetch requests error out with "TypeError: NetworkError when attempting to fetch resource" whenever the user navigates away while there is an ongoing async fetch request. 

Since I am showing a an error message on NetworkError to users this means the user gets flashed with an error message every time they navigate if there is an ongoing fetch request in the background. Beyond flashing an incorrect error message to the user my sentry.io logs fill up with false NetworkError reports. 

Neither Chrome nor Safari does this. 

I am not sure what the ideal solution would be, but throwing an NetworkError when the user cancels the request is just wrong. At the very least it should do something that lets me distinguish an actual error from an canceled network request.
Johan, can you work around the issue by having a small delay between fetch() rejection and showing the error?  Maybe you could suppress the visual error if you get pagehide event?  Not sure on the timing you are seeing.

Anne, is there anything in the spec AFAIK that would require the browser not to reject fetch() promises when the window navigates?
Flags: needinfo?(annevk)
AFAYK I guess?

We added a keepalive member that you can set to true. I suspect the problem here is comment 7. That the timing when requests are aborted is off between Firefox and other browsers.
Flags: needinfo?(annevk)
Problem with pagehide is that it fires after the promise has been rejected and the error show. The promise is also rejected with NetworkError if the user simply hits stop to stop loading the page, in which case pagehide is never fired.
Now that we have abortable fetch we could possibly reject these fetch() calls with AbortError instead of NetworkError.  (This might already happen in FF 57+.) This would let you ignore the AbortError specifically, but report network problems.
I tested and we do fire AbortError when a fetch() is aborted due to navigation.  I did:

1. open this site in FF57: https://fetch-abort-demo.glitch.me/
2. start fetching
3. open web console and run: window.location = 'http://example.com'
4. observe that the AbortError rejection is displayed briefly before the new page is shown

Johan, does this help with your issue?
Flags: needinfo?(johan.sigfrids)
Yes, throwing a distinguishable AbortError on navigation does solve the problem for me.
Flags: needinfo?(johan.sigfrids)
Thanks!  I'm going to close this for now then since the AbortError logic is landed and will be shipping in FF57.
Status: UNCONFIRMED → RESOLVED
Closed: 5 years ago
Flags: needinfo?(bugs)
Resolution: --- → WORKSFORME
This bug doesn't seem to be fixed.

I combined your example with mine and it's still broken. https://firefox-fetch-issue.glitch.me/

I made 3 cases:
1) Slow fetch + redirect to => Not working: Error flash + NetworkError
2) Slow fetch with try-catch + redirect => No error flash, but I still get a NetworkError in the console
3) Slow fetch with try-catch using async await => Error flash + NetworkError

Am I doing something wrong? I've tested it on FF57 and FF58.

The jQuery example also doesn't work in Firefox. (it works fine in Chrome)
Status: RESOLVED → UNCONFIRMED
Resolution: WORKSFORME → ---
Flags: needinfo?(bkelly)
Priority: -- → P2
Andrea, do you have any thoughts on comment 21?  I'm not going to have time to look at this.
Flags: needinfo?(bkelly) → needinfo?(amarchesini)
Component: DOM → DOM: Core & HTML

I believe I am still seeing this issue as well on Firefox 68. Here's my small repro: https://jsfiddle.net/jc4wku5a/

When I watch the debugger when executing this fiddle, I get:

starting
navigating away
caught TypeError: "NetworkError when attempting to fetch resource." TypeError

I see a TypeError instead of an AbortError

So is the issue in comment 23 just that the rejection is with a TypeError, not an AbortError?

Flags: needinfo?(Stephen)

(In reply to Boris Zbarsky [:bzbarsky, bz on IRC] from comment #24)

So is the issue in comment 23 just that the rejection is with a TypeError, not an AbortError?

Yes. comment 18 sounds like there was a change in FF57 that would cause an AbortError. Today in FF68, running the repro from comment 18 and my repro in comment 23 result in a TypeError, not AbortError.

Flags: needinfo?(Stephen)

OK. Andrew, do we want to just mutate this to do the "fire AbortError" thing, or should that be a separate bug (and mark this one invalid, since we do in fact want to terminate fetches on navigation)?

I should note that calling window.stop() while fetching on https://fetch-abort-demo.glitch.me/ throws a TypeError in Chrome and Safari, so we may need to file bugs on them too... It does look to me like the Fetch spec says to reject with an AbortError DOMException in that case, right?

Component: DOM: Core & HTML → DOM: Networking
Flags: needinfo?(bugmail)
Flags: needinfo?(annevk)
Status: UNCONFIRMED → NEW
Ever confirmed: true

I think so, yes. Jake designed this and I thought he also added tests for this scenario, but maybe not.

Flags: needinfo?(annevk) → needinfo?(jaffathecake)
Priority: P2 → P3
Whiteboard: [necko-triaged]
Severity: normal → S4

In Firefox 94.0.2, reloading or clicking a link while a fetch request is being processed still throws a NetworkError. To reproduce, carry out any slow fetch and reload before it is complete.

Any progress with this here? I am getting this error a lot now (FF 100.01... )

You need to log in before you can comment on or make changes to this bug.