代码之家  ›  专栏  ›  技术社区  ›  inf3rno

在chrome中有没有一种方法可以检测HTTP服务器是否响应?

  •  1
  • inf3rno  · 技术社区  · 6 年前

    我有一个脚本,它将一个特定的地址加载到一个子窗口中,并在上面工作。如果我无法访问加载的文档,我想知道浏览器是因为网络或服务器关闭而加载了chrome错误页,还是因为我没有为实际窗口禁用安全和站点隔离而出错。我也一样 DOMException{stack: 'Error: Blocked a frame with origin "..." from accessing a cross-origin frame. 在这两种情况下。我想用 navigator.onLine 和/或使用xhr检查尽可能多的解决方案,但我不确定这是否可行。如果不需要的话,我几天都不想做实验。有人解决了这个问题吗?

    结论:

    最后,我使用了一个带有异步函数的已接受答案的修改版本:

    async function isAlive(url) {
      try {
        await fetch(url, {mode: 'no-cors'});
        return true;
      } catch(error){
        return false;
      }
    }
        
    (async function main(){
      const addresses = [
        'https://google.com',
        'https://reallyf4kewebsite.com',
        '/',
        'https://google.com/foo/bar/baz'
      ];
      const results = await Promise.all(addresses.map((address) => isAlive(address)));
      addresses.forEach((address, index) => console.log(address, results[index]));
    })();
    1 回复  |  直到 6 年前
        1
  •  2
  •   Kaiido NickSlash    6 年前

    通过对服务器执行no-cors请求,您可以知道服务器是否处于活动状态。

    但你将无法获得更多的信息,即错误重定向(404、501等)将被视为活动的。

    这是因为,虽然这个模式允许我们发送请求,就好像没有CORS限制一样,但是您得到的响应实际上是不透明的,除了 “映射到某些响应的URL” 将可以访问我们的脚本。

    function isAlive(url) {
      return fetch(url, {mode: 'no-cors'})
        .then(r => true)
        .catch(r => false);
    }
    
    isAlive('https://google.com')
      .then(r => console.log('google', r));
      
    isAlive('https://reallyf4kewebsite.com')
      .then(r => console.log('reallyf4kewebsite', r));
      
    isAlive('/')
      .then(r => console.log('stacksnippets', r));
    
    isAlive('https://google.com/foo/bar/baz')
      .then(r => console.log('404 redirect', r));