javascript异步_如何使用异步JavaScript检查Internet连接状态

本文介绍了如何使用JavaScript的Fetch API和异步编程来准确检查应用程序的Internet连接状态,因为navigator.onLine属性可能不可靠。通过创建checkOnlineStatus()函数并定期发送请求来检查连接,我们可以实现更稳定的方法。文章强调了在关键数据请求前实时检查连接状态的重要性。
摘要由CSDN通过智能技术生成

javascript异步

Can you use JavaScript to check if your app is connected to the internet?

您可以使用JavaScript检查您的应用程序是否已连接到互联网吗?

In this article, I'll provide an updated answer to this Internet connection detection question. (Whew! Say that fast five times!)

在本文中,我将提供有关此Internet连接检测问题的更新答案。 (哇!快说五遍!)

The solution will use JavaScript's Fetch API and asynchronous code with Async & Await. But first, let's look at an accepted solution and discuss why it may not be the best choice for your application.

该解决方案将使用JavaScript的Fetch API和带有Async&Await的异步代码。 但是首先,让我们看一个公认的解决方案,并讨论为什么它可能不是您的应用程序的最佳选择。

The online property of the navigator interface, navigator.onLine, is frequently used to detect the online and offline status of the browser.

导航界面的在线资产navigator.onLine ,经常被用来检测浏览器的在线和离线状态。

Combined with listeners for online and offline events, it appears to provide a simple solution for developers that is easy to implement.

结合在线和离线事件的侦听器,它似乎为开发人员提供了易于实施的简单解决方案。

让我们看看如何实现navigator.onLine (Let's look at how we'd implement navigator.onLine)

Start by adding a load event listener. When the load event fires, the listener will check the online property of the navigator interface and then display the online status.

首先添加一个加载事件监听器。 当load事件触发时,侦听器将检查导航器界面的online属性,然后显示online状态。

The online property of navigator provides a boolean (true or false) response. To finish the action of the listener, we’ll use a ternary statement to set the status display value.

导航器的online属性提供布尔(true或false)响应。 为了完成侦听器的操作,我们将使用三元语句来设置状态显示值。

window.addEventListener("load", (event) => {
  const statusDisplay = document.getElementById("status");
  statusDisplay.textContent = navigator.onLine ? "Online" : "OFFline";
});

So why the word navigator? Well, it’s a reference to the Netscape Navigator browser from the 90s.

那么,为什么导航这个词呢? 好吧,它是对90年代Netscape Navigator浏览器的引用。

Center an h1 element in your HTML page with the id of “status”. If you apply the JavaScript code above to your page, you should see it display “Online”.

将HTML页中的h1元素居中,其ID为“状态”。 如果将上面JavaScript代码应用于页面,则应该看到它显示“在线”。

But this only updates the h1 element when the page loads. Let’s add offline and online event listeners to update the status display any time either of those events fires.

但这仅在页面加载时更新h1元素。 让我们添加脱机和联机事件侦听器,以在任何一个事件触发时更新状态显示。

window.addEventListener("offline", (event) => {
  const statusDisplay = document.getElementById("status");
  statusDisplay.textContent = "OFFline";
});

window.addEventListener("online", (event) => {
  const statusDisplay = document.getElementById("status");
  statusDisplay.textContent = "Online";
});

We can go to the Application tab of Chrome Dev Tools and click on ServiceWorker to set the browser to respond as if it is offline.

我们可以转到Chrome Dev Tools的“应用程序”标签,然后单击ServiceWorker来设置浏览器,使其像脱机一样做出响应。

Check and uncheck the Offline checkbox a few times. You should see the status display respond immediately to the offline and online events that are fired.

选中并取消选中“脱机”复选框几次。 您应该看到状态显示立即响应所触发的脱机和联机事件。

让我们深入一点 (Let's dig a little deeper)

At first impression, the above seems like a good solution which is fairly simple. Unfortunately, as we read more about the online property of navigator and the online and offline events, we find there is a problem.

乍一看,以上内容似乎是一个很好的解决方案,非常简单。 不幸的是,当我们阅读有关导航器的在线属性以及在线和离线事件的更多信息时,我们发现存在问题。

Searching for navigator.onLine on CanIUse.com shows widespread support for the online | offline status the property provides. However, looking at the notes below the support table, we see that

在CanIUse.com上搜索navigator.onLine显示对在线|的广泛支持。 该属性提供的离线状态。 但是,查看支持表格下方的注释,我们发现

“Online does not always mean connection to the Internet. It can also just mean connection to some network”.
“在线并不总是意味着连接到互联网。 它也可以只意味着连接到某个网络。

Hmm, that throws a wrench in the works a bit.

嗯,这在工作中投入了一点扳手。

So if you really want to determine the online status of the browser, you should develop additional means for checking.

因此,如果您确实想确定浏览器的在线状态,则应开发其他检查方法。

Let’s also take a look at the MDN docs reference for navigator.onLine. MDN web docs backs up the CanIUse.com information and adds additional notes.

我们还要看一下navigator.onLineMDN文档参考 。 MDN Web文档备份CanIUse.com信息并添加其他注释。

“Browsers implement this property differently...you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives...”

“浏览器以不同的方式实现此属性...您不能假设真实值必然意味着浏览器可以访问互联网。 您可能会得到误报……”

And that confirms our fears about using the online property of navigator as our solution for detecting an Internet connection. It is a solution that can wreak havoc in our applications that depend on knowing when outside data sources are available.

这证实了我们对使用navigator的在线属性作为检测Internet连接的解决方案的担忧。 该解决方案可能会严重破坏我们的应用程序,而这些应用程序依赖于何时知道外部数据源何时可用。

One such example is when we are trying to determine if a Progressive Web App is online or not. MDN even recommends,

一个这样的例子就是当我们试图确定Progressive Web App是否在线时。 MDN甚至建议,

“...if you really want to determine the online status of the browser, you should develop additional means for checking.”

“ ...如果您真的想确定浏览器的在线状态,则应开发其他检查方法。”

A quick web search for “navigator online not working” reveals various forum posts where those depending on this property have run into problems.

在网上快速搜索“在线导航器不起作用”时,发现了各种论坛帖子,其中取决于该属性的帖子都遇到了问题。

那么解决方案是什么? (So what’s the solution?)

We need to know when our application is truly connected to the Internet and not just a router or local network. Let’s go back to our JavaScript file and start over.

我们需要知道应用程序何时真正连接到Internet,而不仅仅是路由器或局域网。 让我们回到我们JavaScript文件并重新开始。

The idea is to make a request and handle it gracefully with error catching if it fails. If the request succeeds, we’re online, and if it fails, we’re not.

这个想法是发出一个请求,并在失败时通过错误捕获来优雅地处理它。 如果请求成功,则表明我们在线;如果请求失败,则不是。

We’re going to request a small image at an interval to determine the online status. Modern JavaScript provides the Fetch API and asynchronous code with Async & Await. We will use these tools to accomplish our goal.

我们将每隔一段时间请求一个小图像,以确定在线状态。 现代JavaScript通过Async&Await提供Fetch API和异步代码。 我们将使用这些工具来实现我们的目标。

checkOnlineStatus() (checkOnlineStatus())

Let’s start by creating an async arrow function named checkOnlineStatus. The function will return true or false like the online property of navigator does.

让我们从创建一个名为checkOnlineStatus的异步箭头函数开始。 该函数将返回true或false,就像navigator的online属性一样。

Inside the function, we’ll set up a try block where we await a fetch request for a one pixel image. Ensure your service worker is not caching this image.

在函数内部,我们将设置一个try块,在其中等待对一个像素图像的提取请求。 确保您的服务人员没有缓存该图像。

HTTP response codes between 200 and 299 indicate success, and we’ll return the result of the status code comparison. This will be true if the response status is from 200 to 299 and false otherwise.

200到299之间的HTTP响应代码表示成功,我们将返回状态代码比较的结果。 如果响应状态为200到299,则为true,否则为false。

We also have to provide a catch block that catches the error if the request fails. We’ll return false in the catch block to indicate we are definitely offline if this happens.

我们还必须提供一个catch块,以在请求失败时捕获错误。 如果发生这种情况,我们将在catch块中返回false,以表明我们肯定是离线的。

const checkOnlineStatus = async () => {
  try {
    const online = await fetch("/1pixel.png");
    return online.status >= 200 && online.status < 300; // either true or false
  } catch (err) {
    return false; // definitely offline
  }
};

Next, we’ll use the setInterval method and pass it an anonymous async function. The async function will await the result of our checkOnlineStatus function. We will then use a ternary statement with the result to display the current online status.

接下来,我们将使用setInterval方法并将其传递给匿名异步函数。 异步函数将等待我们的checkOnlineStatus函数的结果。 然后,我们将使用三元语句及其结果来显示当前的在线状态。

For testing this example, set the interval delay to every 3 seconds (3000 milliseconds). This is really too often, though. Checking every 30 seconds (30000 milliseconds) may be enough for your actual needs.

为了测试此示例,请将间隔延迟设置为每3秒(3000毫秒)。 但是,这确实经常发生。 每30秒(30000毫秒)检查一次就可以满足您的实际需求。

setInterval(async () => {
  const result = await checkOnlineStatus();
  const statusDisplay = document.getElementById("status");
  statusDisplay.textContent = result ? "Online" : "OFFline";
}, 3000); // probably too often, try 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.

保存新代码后,让我们重新访问Chrome开发工具中的“应用程序”标签以测试离线响应。

I almost forgot to include the load event listener with async functionality! The load event detection is probably only important if you have a Progressive Web App utilizing a service worker for offline availability. Otherwise, your web page or app simply won't load without a connection.

我几乎忘了包括带有异步功能的load事件监听器! 仅当您具有使用服务工作者提供脱机可用性的Progressive Web App时,负载事件检测才可能很重要。 否则,您的网页或应用程序将无法在没有连接的情况下加载。

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 above interval code is good for displaying a connection status in your app. That said, I don't suggest relying on a connection status that was checked 20 or 30 seconds prior to making a critical data request in your application.

上面的时间间隔代码非常适合在您的应用中显示连接状态。 就是说,我不建议依赖在应用程序中提出关键数据请求之前20或30秒检查的连接状态。

Therefore, you should call the checkOnlineStatus function directly prior to the request and evaluate the response before requesting data.

因此,您应该在请求之前直接调用checkOnlineStatus函数,并在请求数据之前评估响应。

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, we can quickly code a more reliable solution.

尽管navigator.onLine得到广泛支持,但在确定我们的应用程序是否真正连接到Internet时,它提供的结果不可靠。 利用Fetch API和异步JavaScript,我们可以快速编写更可靠的解决方案。

Here’s a link to the code gist on GitHub, and here's a video tutorial I put together:

这是 GitHub上的代码要点的链接 ,这是我放在一起的视频教程:

翻译自: https://www.freecodecamp.org/news/how-to-check-internet-connection-status-with-javascript/

javascript异步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值