我目前正在开发一个 google chrome 扩展程序,用于收集有关用户访问的网页的信息。目前,我的插件能够处理 2xx、3xx、4xx 和 5xx 状态代码。但是,我还需要检测网站何时不存在,并且收到错误代码 ERR_NAME_NOT_RESOLVED
。我如何在 JavaScript 中做到这一点?似乎我的 XMLHttpRequest
甚至无法在不存在的网站上触发。我该如何解决这个问题?
最佳答案
TL;DR:xhr.onerror
应该是您正在寻找的内容,但需要注意。
因此,当您的计算机没有连接时,您可能会收到此错误,并且我认为如果您无法连接到设备的 DNS 服务器。尝试启动 XHR 基本上是失败的。
控制台显示错误might not be preventable by design ,如果你想 try catch 它,你可以使用 xhr 的 .onerror
。 Try-catch 似乎对我不起作用,尽管它看起来应该——可能与其异步性质有关?不确定。
另请记住,.onload
即使出现错误也会运行,尽管由于缺少而可能看起来不像这样存在连接。
如果您有到 DNS 服务器的连接,并且解析的站点根本不存在,则您的 xhr 状态应该为 404,并且不应出现此错误,而如果您没有连接/无法连接到DNS 服务器的 xhr 状态应该为 0,并且应该出现错误。
示例代码:
// you can assign a function because javascript
// in this example, we are using an anonymous function
const xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// error handler example
xhr.onerror = () => {
alert('error');
console.log(xhr);
};
// needs to call as anonymous function to work right
xhr.onload = () => { handleResponse(xhr); };
xhr.send('example.com/action?input=yes');
正如我上面提到的,因为 .onload
和 .onerror
都运行(按顺序),我更喜欢让我的 onload 函数同时处理错误和成功了,希望这对您有用。
const handleResponse = (xhr) => {
if (xhr.state === 200) {
alert('you win');
} else {
alert('error');
}
};
关于javascript - 如何用javascript检测err_name_not_resolved?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211565/