Check if html page exists HTML/Javascript

Asked

Viewed 2,326 times

-4

How do I when clicking the link automatically checks if the page is online? No php.

  • 1

    You did not specify whether you want to check a page from the same domain or not. If it is a domain other than your application, you will not be able to do this verification on behalf of CORS.

  • 1

    I think duplicated this https://answall.com/questions/123868/verifi-se-url-existe/123966#123966, or at least related.

3 answers

9

If the site you are trying to check is on a different domain you will probably have lock with CORS, read on:

HTTP Access Control (CORS)

Plus it’s important to know that offline sites can be anything, it can be a disabled page that emits an HTTP status code or it can actually be offline ("off") and won’t even connect, so the @13dev response won’t work:

200: function () {
    alert('site esta on!');
},
400: function() {
    alert("site off!");
}

Because this script only checks the HTTP status, besides that in jQuery there is no attribute method: the correct is type:

The best to check with jQuery would be to use so:

$.ajax({
    url: "http://meusite.com",
    type: "HEAD"
}).done(function () {
     alert('Online');
}).fail(function () {
     alert('Provavelmente offline');
});

However this still has the problem of the Cors probably.

The @Godfrey code may also not work in modern browsers (maybe in the future), this because it is in synchronous mode and this is in disuse by browsers and will soon be removed:

var xhr = new XMLHttpRequest();
xhr.open("GET",uri,false);
xhr.send(null);
if(xhr.status == 200) { // A página está online.
     return xhr.responseText;
}

The best is to use onreadystatechange:

var xhr = new XMLHttpRequest();
var uri = "http://site.com";

xhr.open("GET", uri, true); //Defina TRUE

//Usando callback
xhr.onreadystatechange = function () {
    if(xhr.status >= 200 && xhr.status < 300) { // A página está online.
         alert("online");
    } else {
         alert("provalmente offline");
    }
};
xhr.send(null);

No guaranteed way to check front-end connectivity

For reasons of Cors as I already said there is no way to check whether a site is actually online, unfortunately the only reliable solution is using back-end, even if it has not been what you requested yet yes I recommend you review this.

Examples in PHP:

Checking if a site is available and port 80 (which is the HTTP port available)

if (!fsockopen("www.site-externo.com", 80, $errno, $errstr, 10)) {
    echo "Offline";
} else {
    echo "Online";
}

The previous code only checks if the site is online, but does not check if the page you consulted is "valid" (returns HTTP code between 200 and "299"), however if you want to check this you can also use curl:

<?php

$url = 'https://www.site-externo.com/pagina-especifica';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

//Define um User-agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

//Não retorna a resposta
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);

//Resposta
$data = curl_exec($ch);

if($data === false) {
    echo 'Offline, detalhes do erro: ' . curl_error($ch);
} else {
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpcode >= 200 && $httpcode < 300) {
        echo 'Online';
    } else {
        echo 'Offline, resposta HTTP: ' . $httpcode;
    }
}

Another way not so sure, but still more guaranteed than with Ajax would use document.createElement('script') with a Resource .js of the external site.

  • 1

    Ho Good idea, (51) rs, tell me the url enter where?

  • 1

    @Leocaracciolo see if you can understand the codes now, anyway the answer is explain that these solutions that 13dev and Godfrey posted are not practical and can cause more problems than solve something.

  • I understood, only that it was missing the Uri in its answer.

  • 2

    @Guilhermenascimento Cara... He made it explicit that he does not want to check the backend.

  • @Godfreytheking the answer speaks much more than another domain, speaks: "if it’s another domain, if it’s not going to work"

  • @Then remove the unnecessary part of the question. Sockets, etc... Corresponds to the backend.

  • 2

    @Godfreytheking has nothing unnecessary, I answer the question within the statement, explained the difference of HTTP response and of a de facto offline server and the examples in PHP are an additional that help to understand the differences between socket and HTTP response.

  • @Godfreytheking out that it is not very logical to check if the site you are already browsing this online, so it is far more likely that he is really wanting to check if an external site is online.

  • 2

    @Guilhermenascimento my answer was turned to the simplest as I mentioned, but I’ve already edited you were right, thank you for the information + 1!

  • 1

    @13dev thank you!

Show 5 more comments

2

The simplest of all would be to make an ajax request to check if the page exists:

$.ajax({
    url: "http://meusite.com",
    type: "HEAD"
}).done(function() { 
      alert('Site existe!');
}).fail(function() { 
      alert('Site não existe!');
})

OBS Remembering that this will not work if the domain to be searched is not the same as the application. On account of the header Access-Control-Allow-Origin

  • Speaks master I think there is something strange in your reply, statusCode 404 Site On ?

  • confused mind ! already this correct ahah, thank you is that I did not notice!

  • 3

    Remembering that this will not work if the domain to be searched is not the same as the application. Because of the header Access-Control-Allow-Origin.

  • @Godfreytheking you’re absolutely right I’ll edit!

0

You did not specify if you want to check if the page belongs to the same domain and if you want the answer using jQuery... Anyway:

function checkPage() {
    // Colocar aqui a url.
    var url = ''
    var xhr = new XMLHttpRequest();
    xhr.open("GET",url ,false);
    xhr.send(null);
    if(xhr.status == 200) { // A página está online.
     return xhr.responseText;
    }

    // Está offline.
    return null;
}
  • @Leocaracciolo, I could not understand his doubt. For example: var url = "meudominio.com.br".

  • Yep, problem with typing ;)

  • Blz, it was just to get your answer straight

Browser other questions tagged

You are not signed in. Login or sign up in order to post.