如何用javascript检测err_name_not_resolved?

时间:2016-07-05 19:48:51

标签: javascript google-chrome google-chrome-extension dns xmlhttprequest

我目前正在开发一个Google Chrome扩展程序,用于收集有关用户访问的网页的信息。目前,我的插件能够处理2xx,3xx,4xx和5xx状态代码。但是,我还需要检测网站何时不存在,并且我收到错误代码ERR_NAME_NOT_RESOLVED。我如何在javascript中执行此操作?似乎我的XMLHttpRequest甚至无法在不存在的网站上触发。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

对于现有网站,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?');
});

答案 1 :(得分:0)

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');
  }
};