detect 404 error on page load

南楼画角 提交于 2019-11-27 16:33:14

问题


I am embedding a google map in my website and sometimes google responds with a 404 error. I know I should know this, but I can't remember and I cannot find it quickly. None of the other 404 iframe related questions on this site were ever answered.

How do I check if there is a 404 response in javascript? I plan to call location.reload() when the response is 404.

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

The error code is:

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

I tried this: It didn't help.

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

回答1:


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

Use this function and pass the URL as Parameter.if the status is not 404 then nothing will happen or you can do something else it will refresh the page as per your requirement.




回答2:


I know this is an old question, but here is an updated way of doing it with fetch (doesn't work on 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
  }
});


来源:https://stackoverflow.com/questions/26630650/detect-404-error-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!