alfg / ping.js Goto Github PK
View Code? Open in Web Editor NEW:bell: Ping the web with Javascript.
Home Page: https://github.com/alfg/ping.js
:bell: Ping the web with Javascript.
Home Page: https://github.com/alfg/ping.js
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).
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.
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!
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.
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.
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
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
ping.js is already small, and after merging #1 would be smaller; But I suggest the following:
callback && callback(pong)
would be enough? Maybe if there's no callback we can default to console.log
so it's still useful.WDYT?
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
Hello,
Why my favicon.ico is dowloaded several times so I receive several times ping data?
Thanks
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?
Every time I try this with a known web address it returns Error.
Very cool tool guys!
Love this.
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?
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
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://"
}
The jQuery JSFiddle example only shows "error" and no ping times.
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.
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]'}
]
},``
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);
}
});
what if ping fails, like pinging youtube.com from china?
does callback function always get response time and not status or error code?
It allows pinging and returns responses even if you put some invalid IP address like 192.168.20.5000 etc.
title really says it all tbh
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.