Detect 404 error while loading page

I embed a google map on my site, and sometimes google responds with a 404 error. I know I need to know this, but I cannot remember, and I cannot find it quickly. None of the 404 iframe-related questions on this site ever answered.

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

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

Error code:

 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 did not help.

 var url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q'; if (url.statusCode === '404'){ window.location.reload(); } 
+4
source share
2 answers
 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 a parameter. If the status is not 404, nothing will happen or you can do something else, it will refresh the page according to your requirement.

+10
source

I know this is an old question, but here is an updated way to do it with fetch (doesn't work in IE)

 function urlExists(url, callback) { fetch(url) .then(function(status) { callback(ok) } } var 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 } } 
+2
source

Source: https://habr.com/ru/post/956008/


All Articles