我目前正在开发一个google chrome扩展,它可以收集用户访问的网页的信息。目前,我的插件可以处理2xx,3xx,4xx和5xx状态码。但是,当网站不存在时,我还需要检测,我得到的错误代码是ERR_NAME_NOT_RESOLVED。我如何在javascript中做到这一点?似乎我的XMLHttpRequest甚至不能在不存在的网站上触发。我该如何解决这个问题?
发布于 2021-05-16 12:30:09
TL;DR:xhr.onerror应该是你想要的,但有个警告。
所以,当你的电脑没有连接,我想如果你不能连接到你设备的DNS服务器时,你会得到这个错误。尝试启动XHR基本上是一个失败。
似乎在控制台might not be preventable by design中显示了错误,如果您想尝试捕获它,您可以使用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');
}
};发布于 2016-07-22 06:18:59
XMLHttpRequest的onreadystatechange侦听器在这里对现有站点触发2+次,对于不存在的站点只触发一次status属性等于0的监听器,所以下面的代码适用于我:
function xhrGetStatus(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url);
xhr.onreadystatechange = function(e) {
xhr.onreadystatechange = null;
callback({status: xhr.status, statusText: xhr.statusText});
};
xhr.send();
}
xhrGetStatus('http://abc123.com', function(r) {
console.log(r.status ? r.status : 'No such site?');
});https://stackoverflow.com/questions/38211565
复制相似问题