Makim Api Call Again if Conmection Fails
Can you apply JavaScript to check if your app is connected to the net?
In this article, I'll provide an updated answer to this Cyberspace connection detection question. (Whew! Say that fast 5 times!)
The solution will use JavaScript's Fetch API and asynchronous code with Async & Await. Just first, permit's look at an accustomed solution and hash out why information technology may not exist the best selection for your application.
navigator.onLine
The online belongings of the navigator interface, navigator.onLine, is oftentimes used to detect the online and offline status of the browser.
Combined with listeners for online and offline events, it appears to provide a simple solution for developers that is easy to implement.
Let's look at how we'd implement navigator.onLine
Kickoff by adding a load outcome listener. When the load event fires, the listener volition check the online property of the navigator interface and then display the online status.
The online belongings of navigator provides a boolean (true or simulated) response. To finish the action of the listener, we'll use a ternary argument to set the status display value.
window.addEventListener("load", (upshot) => { const statusDisplay = document.getElementById("condition"); statusDisplay.textContent = navigator.onLine ? "Online" : "OFFline"; }); Then why the word navigator? Well, it's a reference to the Netscape Navigator browser from the 90s.
Middle an h1 element in your HTML page with the id of "status". If you apply the JavaScript code higher up to your folio, you should see it display "Online".
But this only updates the h1 element when the page loads. Let's add offline and online event listeners to update the condition display whatsoever time either of those events fires.
window.addEventListener("offline", (event) => { const statusDisplay = certificate.getElementById("status"); statusDisplay.textContent = "OFFline"; }); window.addEventListener("online", (effect) => { const statusDisplay = document.getElementById("status"); statusDisplay.textContent = "Online"; }); Nosotros can go to the Awarding tab of Chrome Dev Tools and click on ServiceWorker to set the browser to respond as if it is offline.
Bank check and uncheck the Offline checkbox a few times. You should meet the condition display respond immediately to the offline and online events that are fired.
Allow'southward dig a little deeper
At offset impression, the above seems like a practiced solution which is fairly simple. Unfortunately, as we read more about the online property of navigator and the online and offline events, we discover there is a problem.
Searching for navigator.onLine on CanIUse.com shows widespread back up for the online | offline status the property provides. However, looking at the notes below the back up table, we see that
"Online does not ever mean connectedness to the Internet. Information technology can also just mean connection to some network".
Hmm, that throws a wrench in the works a fleck.
Then if you really want to determine the online status of the browser, you should develop additional ways for checking.
Let's too take a expect at the MDN docs reference for navigator.onLine. MDN web docs backs upwardly the CanIUse.com information and adds additional notes.
"Browsers implement this property differently...you cannot assume that a true value necessarily ways that the browser tin access the internet. You could be getting imitation positives..."
And that confirms our fears about using the online property of navigator as our solution for detecting an Internet connexion. Information technology is a solution that can wreak havoc in our applications that depend on knowing when exterior data sources are bachelor.
1 such instance is when we are trying to determine if a Progressive Web App is online or not. MDN even recommends,
"...if yous really want to determine the online status of the browser, you should develop additional means for checking."
A quick web search for "navigator online non working" reveals various forum posts where those depending on this holding have meet problems.
And then what's the solution?
Nosotros need to know when our awarding is truly continued to the Internet and not simply a router or local network. Let's go back to our JavaScript file and start over.
The idea is to brand a request and handle it gracefully with mistake communicable if it fails. If the asking succeeds, we're online, and if it fails, we're not.
Nosotros're going to request a small epitome at an interval to determine the online status. Modern JavaScript provides the Fetch API and asynchronous code with Async & Await. We will apply these tools to accomplish our goal.
checkOnlineStatus()
Allow'southward start by creating an async pointer office named checkOnlineStatus. The function will return true or simulated like the online property of navigator does.
Inside the function, we'll prepare up a try block where we await a fetch request for a one pixel prototype. Ensure your service worker is non caching this paradigm.
HTTP response codes between 200 and 299 indicate success, and nosotros'll render the event of the condition code comparison. This will be true if the response status is from 200 to 299 and false otherwise.
We as well have to provide a grab block that catches the error if the request fails. Nosotros'll return faux in the catch block to point we are definitely offline if this happens.
const checkOnlineStatus = async () => { try { const online = await fetch("/1pixel.png"); return online.condition >= 200 && online.status < 300; // either true or false } grab (err) { return faux; // definitely offline } }; Side by side, we'll use the setInterval method and laissez passer it an bearding async function. The async function will expect the result of our checkOnlineStatus part. We volition then apply a ternary statement with the effect to brandish the current online condition.
For testing this example, set the interval filibuster to every iii seconds (3000 milliseconds). This is really too often, though. Checking every xxx seconds (30000 milliseconds) may be plenty for your actual needs.
setInterval(async () => { const result = await checkOnlineStatus(); const statusDisplay = certificate.getElementById("status"); statusDisplay.textContent = result ? "Online" : "OFFline"; }, 3000); // probably too oft, effort 30000 for every 30 seconds With our new code saved, let's revisit the Application tab in Chrome Dev Tools to test the offline response.
I well-nigh forgot to include the load event listener with async functionality! The load result detection is probably simply important if you accept a Progressive Web App utilizing a service worker for offline availability. Otherwise, your web page or app simply won't load without a connexion.
Here's the new load event listener:
window.addEventListener("load", async (event) => { const statusDisplay = document.getElementById("status"); statusDisplay.textContent = (await checkOnlineStatus()) ? "Online" : "OFFline"; }); A Final Thought
The in a higher place interval code is proficient for displaying a connection status in your app. That said, I don't suggest relying on a connexion condition that was checked 20 or 30 seconds prior to making a disquisitional data request in your application.
Therefore, you lot should call the checkOnlineStatus role directly prior to the asking and evaluate the response before requesting data.
const yourDataRequestFunction = async () => { const online = await checkOnlineStatus(); if (online) { // make data request } } Conclusion
While navigator.onLine is widely supported, it provides unreliable results when determining if our applications are truly connected to the Internet. Utilizing the Fetch API and asynchronous JavaScript, nosotros tin can quickly code a more reliable solution.
Here's a link to the lawmaking gist on GitHub, and here'south a video tutorial I put together:
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Become started
Source: https://www.freecodecamp.org/news/how-to-check-internet-connection-status-with-javascript/
0 Response to "Makim Api Call Again if Conmection Fails"
Post a Comment