在页面加载时检测404错误

时间:2014-10-29 12:42:03

标签: javascript http-status-code-404

我在我的网站中嵌入了谷歌地图,有时谷歌会回复404错误。我知道我应该知道这一点,但我无法记住,我无法快速找到它。此网站上的其他404 iframe相关问题均未得到解答。

如何检查javascript中是否有404响应?我计划在响应为404时调用location.reload()。

<iframe src="https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q" width="640" height="480"></iframe>

错误代码是:

GET https://khms0.googleapis.com/kh?v=159&hl=en&x=784456&y=1636828&z=22&token=122715 404 (Not Found)

我试过这个:它没有帮助。

var url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q';
if (url.statusCode === '404'){
    window.location.reload();
}

2 个答案:

答案 0 :(得分:13)

var url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q';
function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status != 404)
        //  do something
    else
        window.location.reload();
}

使用此功能并将URL作为参数传递。如果状态不是404,则不会发生任何事情,或者您可以执行其他操作,它将根据您的要求刷新页面。

答案 1 :(得分:5)

我知道这是一个老问题,但这里有一个更新的方法,用fetch做这个(在IE上不起作用):

function urlExists(url, callback) {
  fetch(url, { method: 'head' })
  .then(function(status) {
    callback(status.ok)
  });
}

let url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q';

urlExists(url, function(exists) {
  if (exists) {
    // it exists, do something
  } else {
    // it doesn't exist, do something else
  }
});