How to reload the original url after recovering from network disconnection

前端 未结 1 1258
Happy的楠姐
Happy的楠姐 2021-01-28 23:48

I have webapp which uses a service worker that detects, when the network is offline, and serves a cached offline page.

I have a case where:

  • the progra
1条回答
  •  无人及你
    2021-01-29 00:28

    The problem was cause by the following situation:
    My wep app is a Single Page Application (SPA) where the DOM tree is changes in the front-end via ajax commands.
    In my case, the function that waits for the fetch response expects content type application/json.
    When the service worker detects a network disconnect, it returns a response of content type: text/html (the offline page).
    Since there is no response error, the function tries to extract response.json() but because the type is text and not json, (due to the offline page) the parsing fails and throws an error, and the text/html data (the offline page) is ignored.
    Forcing to reload the page with window.location.href = response.url causes the program to load the page, which changes the address bar, which prevents from the user to recover the original page via refresh, when the network re-connects

    The solution is to:

    • detect if the fetch failed because of network disconnect
      I do this by checking if(response.url == "https://localhost/static/offline/offline.html")
    • if yes, replace the content of the existing page by using: document.getElementsByTagName("html")[0].innerHTML = dataAsText;

      This has the added benefit that if the network disconnect happens while we are on another page, once the network re-connects, refresh will load the last visited page (keep the last state)

    • stop using window.location.href to load the offlin page. This has the benefits of: prevent reloading of the page which reloads the headers and the resources, which slows down the response, and prevent changing the link in the address bar, so that the user can restore the last page by just refreshing the page, when the network re-connects.

    0 讨论(0)
提交回复
热议问题