Giter VIP home page Giter VIP logo

ping.js's Introduction

Ping.js

npm npm

Ping.js is a small and simple Javascript library for the browser to "ping" response times to web servers in Javascript! This is useful for when you want to display realtime ping times on a status page which are relative to the user.

See Notes below for how this works.

JS Fiddle Example: http://jsfiddle.net/alfg/sr0tpn4x/

Example in jQuery: http://jsfiddle.net/alfg/xjqbvt2o/

Usage

This module is for the browser only as it depends on the brower's Image API.

  • Download the distribution files in dist to your project.
var p = new Ping();

// Using callback
p.ping("https://github.com", function(err, data) {
  // Also display error if err is returned.
  if (err) {
    console.log("error loading resource")
    data = data + " " + err;
  }
  document.getElementById("ping-github").innerHTML = data;
});

// You may use Promise if the browser supports ES6
p.ping("https://github.com")
  .then(data => {
    console.log("Successful ping: " + data);
  })
  .catch(data => {
    console.error("Ping failed: " + data);
  })

or import as a module:

$ npm install ping.js
import Ping from 'ping.js';

or use the jsdelivr CDN:

<script src="https://cdn.jsdelivr.net/gh/alfg/[email protected]/dist/ping.min.js" type="text/javascript"></script>

See demo/react-example for an example in React.

API

var p = new Ping(opt);

Ping([options])

Create Ping instance.

options

  • Type: Object
  • favicon: Override the default favicon.ico image location.
  • timeout: Optional - Set a timeout in milliseconds.

p.ping(source, callback)

Creates a ping request to the source. Returns a promise that resolves and rejects to the response time in milliseconds, or if the browser does not supports Promise, returns undefined.

  • source: IP address or website URL, including protocol and port (optional). Example: https://example.com:8080
  • callback(err, ping): Optional - Callback function which returns an error and the response time in milliseconds.

Development

Install project:

git clone https://github.com/alfg/ping.js.git
cd ping.js
npm install
npm install -g grunt-cli

Run grunt to build distribution files:

grunt

Open demo/index.html in a browser to test results.

Notes

Javascript itself doesn't have a native way of sending a "ping", so results may not be completely accurate. Since xhr 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

MIT License © Alfred Gutierrez

ping.js's People

Contributors

alfg avatar eldonmcguinness avatar ensemblebd avatar khang-nd avatar ronnyo avatar shaundr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ping.js's Issues

How to ping proxy server?

First of all thanks for this great library :D

Is there any way to ping proxy server ??
When I ping ip from the command line its working
But showing error in this library
For instnace how can I ping this proxy below?
24.154.112.20:8080

Object as parameter

With the list of parameters growing it might be prudent to allow a built object to be passed into the ping call.

Ex.

{
    "host" : "Google.com",
    "timeout": 5000,
    "proto" : "https://"
}

Ping Lib is not recognized

I did installed the ping library and I tried to import and use the same. But when I import it is not being accepted and shows the following error on hover.

image

Could not find a declaration file for module 'ping.js'. 'c:/Users/vn509wj/Desktop/workspace/ui-retaillink-react/node_modules/ping.js/index.js' implicitly has an 'any' type.
  Try `npm install @types/ping.js` if it exists or add a new declaration (.d.ts) file containing `declare module 'ping.js';`ts(7016)
Could not find a declaration file for module 'ping.js'. 'c:/Users/vn509wj/Desktop/workspace/ui-retaillink-react/node_modules/ping.js/index.js' implicitly has an 'any' type.

Below is the module and plugin in my web pack
``plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new CopyWebpackPlugin([
{ from: 'src/libs/js', to: 'vendor/d3'}
]),
new CopyWebpackPlugin([
{from: 'src/custom', to: 'vendor/custom'}
]),
new HtmlWebpackIncludeAssetsPlugin({
assets: ['vendor/d3/d3.v3.min.js','vendor/d3/d3.tip.v0.6.3.js'],
append: false,
publicPath: 'rl-portal/'
})

],
module: {
loaders: [
{test: /.d.ts$/, include: path.join(__dirname, 'src'), loader: 'babel', query: { plugins: ['transform-decorators-legacy'], presets: 'es2015'}},
{test: /.js$/, include: path.join(__dirname, 'src'), loader: 'babel', query: { plugins: ['transform-decorators-legacy'], presets: 'es2015'}},
{test: /.jsx?$/, loader: 'babel', exclude: /node_modules/, query: { plugins: ['transform-decorators-legacy', 'transform-es2015-destructuring', 'transform-object-rest-spread'], presets: ['es2015', 'react']}},
{test: /(.css)$/, loaders: ['style', 'css?sourceMap']},
{test: /.less$/, loader: "style!css!less"},
{test: /.eot(?v=\d+.\d+.\d+)?$/, loader: "url?limit=100000&mimetype=file"},
{test: /.(woff|woff2)$/, loader: "url?prefix=font/&limit=50000"},
{test: /.ttf(?v=\d+.\d+.\d+)?$/, loader: "url?limit=20000&mimetype=application/octet-stream&name=fonts/[hash].[ext]"},
{test: /.svg(?v=\d+.\d+.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml&name=images/[hash].[ext]"},
{test: /.json$/, loader: 'json-loader'},
{test: /.(png|jpg|gif)$/,loader: 'url?limit=25000&name=images/[hash].[ext]'},
{test: /.pdf$/,loader: 'file?name=[name].[ext]'}
]
},``

Difficulty with timeout

When specifying timeout option, it produces a double callback execution.

So I've adjusted the code as needed, figured I would share.

/*
 *  ping.js - v0.2.1
 *  Ping Utilities in Javascript
 *  http://github.com/alfg/ping.js
 *
 *  Made by Alfred Gutierrez
 *  Under MIT License
 */
/**
 * Creates a Ping instance.
 * @returns {Ping}
 * @constructor
 */
var Ping = function(opt) {
    this.opt = opt || {};
    this.favicon = this.opt.favicon || "/favicon.ico";
    this.timeout = this.opt.timeout || 0;
};

/**
 * Pings source and triggers a callback when completed.
 * @param source Source of the website or server, including protocol and port.
 * @param callback Callback function to trigger when completed. Returns error and ping value.
 * @param timeout Optional number of milliseconds to wait before aborting.
 */
Ping.prototype.ping = function(source, callback) {
	var self = this;
    self.img = new Image();
	self.wasSuccess=false;
    var timer;

    var start = new Date();
    self.img.onload = function(e) {
		self.wasSuccess=true;
		if (!self.timeout) pingCheck.call(self,e); // discard the successful event if self.timeout is used. Because it responded after the timeout expiry.
	};
    self.img.onerror = function(e) {
		self.wasSuccess=false;
		if (!self.timeout) pingCheck.call(self,e);
	};
	
    if (self.timeout) { timer = setTimeout(function(){
		pingCheck.call(self,event,true);
	}, self.timeout); }

    /**
     * Times ping and triggers callback.
     */
    function pingCheck(e, isTimeout) {
		if (typeof(isTimeout)==='undefined') isTimeout=false;
        if (timer) { clearTimeout(timer); }
        var pong = new Date() - start;

        if (typeof callback === "function") {
            if (!this.wasSuccess) {
                //console.error("error loading resource");
                return callback("error", pong);
            }
            return callback(null, pong);
        }
    }

    self.img.src = source + self.favicon + "?" + (+new Date()); // Trigger image load with cache buster
};

if (typeof exports !== "undefined") {
    if (typeof module !== "undefined" && module.exports) {
        module.exports = Ping;
    }
} else {
    window.Ping = Ping;
}

Also included was a bugfix for timeout call to pingCheck in which case the [e] (event) is not defined, causing fatal error (I added an undefined || check).

code still seems to return requests on timeout

while testing the timeouts, it seemed to me that even if the timeout is hit, you will still get the result of call when it happens (i.e. if you put a timeout of 300ms and the call requires 330ms, you would get a "timeout" result (error fixed in my PR) at 300ms but also the result of the original call at 330ms, whether OK or an http error. Is there any way to discard such "late" running request? I have not extensively tested this but am somewhat concerned about memory pileup if it happens too often with regards to the frequency of the pings

Shave some more bytes

ping.js is already small, and after merging #1 would be smaller; But I suggest the following:

  • Shorter banner for minified version
  • No version property - Not sure if this is really useful
  • Maybe the type checking for callback can be skipped and callback && callback(pong) would be enough? Maybe if there's no callback we can default to console.log so it's still useful.

WDYT?

ReferenceError: Image is not defined

I get the error "ReferenceError: Image is not defined" when trying to start it, here is the code:

const Ping = require('ping.js');
var p = new Ping();

p.ping('https://github.com', function(err, data) {
if (err) {
console.log('error loading resource');
data = data + ' ' + err;
} else {
console.log(data);
}
});

Errors

Every time I try this with a known web address it returns Error.

what if ping fails

what if ping fails, like pinging youtube.com from china?
does callback function always get response time and not status or error code?

SSL support

Like this tool !

Had problems with HTTPS request that did not work for me so i added a new function arg (secure) and edited a bit of the src stuff

And this works great

line15

Ping.prototype.ping = function(source, callback, secure) {

line 32

this.img.src = ((secure) ? "https://":"//") + source + "/?" + (+new Date()); // Trigger image load with cache buster

Offline / error catching logic?

Just tried it out with internet off and it returns a solid ping of 2 to 3ms in the callback...
Or is this not within the scope of the project?

Response times are not correct

Hi,

Response times given by ping.js are totally different then from real ping.
For example:
google.com cmd ping 28ms vs ping.js 385ms
my router cmd ping 1-2 ms vs ping.js 1 -21ms (looks like random numbers)
I like idea of this script but actually something is wrong, make it almost useless.

Response time different.

May I please ask why response time different when I use cmd in my computer compared to browser.

I do get 10ms when i ping to am.guildbit.com while i do get around 200 when i ping from my browser.
Thank you.

Not working properly.

ping delay returning is more as compared to the terminal. when i ping the same site from terminal it gives a less ping time as compared to the ping.js script.

Ping failed to return time

Ping what is the reason for the return of a domain name that does not exist?

github.xxx//favicon.ico?1504163468779:1 GET https://github.xxx//favicon.ico?1504163468779 net::ERR_NAME_NOT_RESOLVED
error 12
error loading resource

this 12 Why would you return?

ping ipaddress

Hi
ich mag dieses Projekt da ich lokal auf meinem Rechner ohne einen Server etwas pingen kann.
Aber nun möchte ich eine feste ip adresse pingen, leider bekomme ich da einen fehler.
Leider bin ich in JavaScript nicht so erfahen und webprogrammierung.
Könnte mir jemand helfen wie ich eine beliebige ipadresse pingen könnte?!?
ich würde gern nicht nur server im internet damit auf erreichbarkeit prüfen sondern auch gern rechner bzw. geräte die in meinem internen Netz laufen sollten.
559 / 5000
Übersetzungsergebnisse
Hi
I like this project because I can ping something locally on my computer without a server.
But now I want to ping a fixed ip address, unfortunately I get an error.
Unfortunately I am not that experienced in JavaScript and web programming.
Could someone help me how I could ping any ip address?!?
I would like to use it not only to check the accessibility of the internet server, but also to check computers or devices that should run in my internal network.

I hope someone can help me in the short term.
Thank you so much
orichienal

Getting RED error in console when no return

image

Hi, is it possible to put at OFF the red part in the console when there is an error ? (I'd keep only my console.log("no response"), I have this red thing :)

Thanks,

Lunar

Better data from HTTP requests

Since we can't use IMCP in JS, would it be possible to build into this library the ability to run the test several times and output the average of the tests? Perhaps input the number of tries as an option? Thank you for this very useful tool!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.