How to Ping in Javascript

Save

There are many reasons why you might want to ping an external domain from a script in your web page. You may be passing variables to a server and want to ensure that it is responsive before doing so. You may be accessing a file that is mirrored by many different external sites and want to automatically attempt to access another if the first one is down. Whatever the case, you can ping an external domain in JavaScript if you have the address of an image that is hosted on it.

  • Open the web page on which you wish to perform the ping in your preferred text editor.

  • Insert the following code between the opening and closing <body> tags of the web page:

    <script type="text/javascript">

    var ImageObject = new Image();

    ImageObject.src = "http://myserver.com/pic.jpg";

    if(ImageObject.height>0){

    alert('The domain is available.');

    }

    </script>

    Substitute the complete URL of the image hosted on the external domain for the value of ImageObject.src above.

  • Save and publish your web page. When accessed, it will check to see if the image on the domain returns a height value greater than zero. If it gets a response from the domain, it will cause an alert box to pop up stating that the domain is up and running.

References

  • Photo Credit Stockbyte/Stockbyte/Getty Images
Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!