Eseguire un PING in Javascript con ping.js

Mattepuffo's logo
Eseguire un PING in Javascript con ping.js

Eseguire un PING in Javascript con ping.js

ping.js è una piccola libreria che ci permette di eseguire una sorta di PING in Javascript.

Da prendere con le molle ovviamente; guardate la descrizione direttamente dal canale di GitHub:

Javscript itself doesn't have a native way of sending a "ping", so results may not be completely accurate. Since ajax requests are affected by cross-domain issues (CORS), they are blocked by default. ping.js is using a method of loading a favicon.ico image from any host and timing the response time. If the favicon image doesn't exist, an error is returned along with the ping value. If there's a better way to do this in Javascript, feel free to create an issue, or pull request so I can review.
License

Vediamo un esempio:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>TEST</title>
        <link rel="stylesheet" href="pretty-print-json.css">
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"
                integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
                crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/gh/alfg/ping.js@0.2.2/dist/ping.min.js" type="text/javascript"></script>
        <script>
            var ping = new Ping();

            ping.ping("https://github.com", function (err, data) {
                console.log("https://github.com");
                if (err) {
                    console.log(err);
                }
                console.log(data);
            });
        </script>
    </head>
    <body>
    </body>
</html>

Viste le premesse di prima, considerate che potrebbe non funzionare con tutti gli url.

Di sicuro non funziona se provate a pingare un indirizzo IP secco.

Comunque tenete presente questa libreria se avete necessità del genere.

Enjoy!


Condividi

Commentami!