skip to Main Content

According to this answer on Stackoverflow, one of the reason a "Failed to fetch" can occur is because of navigation.

Browser aborted — most likely due to navigation to another page before the fetch completes

How can I handle this specific error in simple fetch query?

fetch("https://xxx.yyy/").then(e => e);

I don’t want to handle all "failed to fetch" error, only the ones that are triggered because of navigation.

2

Answers


  1. You could listen for the navigation event and then use an AbortController before they navigate https://developer.mozilla.org/en-US/docs/Web/API/AbortController

    Login or Signup to reply.
  2. I can think of only one way, to flag the navigation start and then check the flag in your handler.

    Unfortunately, the navigate event is not very well supported so you might want to use beforeunload instead.

    navigateStart = false;
    addEventListener("navigate", (event) => {
        navigateStart = true;
    });
    fetch("https://xxx.yyy/").then(e => e).catch(e => {
        if (navigateStart) {
            // This is most likely due to a navigation, handle accordingly here.
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search