Detect if page 404s with Javascript

ellescuba27

Member
Messages
273
Reaction score
3
Points
18
Hi! Today, I'm going to give you a Javascript to detect if a page 404s, 403s, 418s or 111s (no wait, that's email). Anything beisdes error 200, pretty much. But you say "with server side languages, why do I need Javascript to detect this"? PHP works fine for the most part, but the problem comes in when something might work on the client side and not the server side. For example, many websites will give you error 401 unauthorized if you aren't logged in. You can't program PHP to log into a site THEN check if it is still error 401, it's simply beyond possibility. But the user might be logged in! So one practical purpose of this script might be to check if the user is logged into a site, because if they aren't it gives error 401. Anyways I can tel by this point in time you are just dying to have it so here it is:
Code:
(function() { 
try
  {
            var script = document.createElement('script'); 
        script.type = 'text/javascript';    
        script.onerror = function(){alert("Error!");};
        script.onload = function(){alert("Connection successful on client side");};
        script.src = 'http://google.ca';
        document.getElementsByTagName("body")[0].appendChild(script);


  }
catch(err)
  {
    // Fail silently.
  }
        })
    ();
If you try changing google.ca to a non-existent address, it will 404 and say "Error!" but if you use a good web address like x10hosting.com , it will only take a few moments to say "Connection successful on client side". You can try it in your browser's web console, it works perfectly fine for me running Chrome. Enjoy :)
 
Top