-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
863 lines (787 loc) · 28.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PingIt - Network Monitor</title>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css"
rel="stylesheet"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="max-w-4xl mx-auto p-8 pb-24">
<!-- <div class="max-w-4xl mx-auto p-8 pb-20"></div> -->
<!-- Header -->
<div class="text-center mb-8 sm:mb-12">
<div
class="bg-gradient-to-r from-gray-100 to-gray-50 w-12 h-12 sm:w-16 sm:h-16 rounded-xl sm:rounded-2xl mx-auto mb-4 sm:mb-6 flex items-center justify-center"
>
<svg
class="w-6 h-6 sm:w-8 sm:h-8 text-gray-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13 10V3L4 14h7v7l9-11h-7z"
/>
</svg>
</div>
<h1 class="text-3xl sm:text-4xl font-semibold text-gray-800 mb-2">
PingIt
</h1>
<p class="text-sm sm:text-base text-gray-600">
Real-time network monitoring, simplified
</p>
</div>
<!-- URL Input Section -->
<div class="bg-white rounded-xl sm:rounded-2xl shadow-sm overflow-hidden">
<div class="p-4 sm:p-6">
<div class="mb-4 sm:mb-6">
<label class="block text-sm font-medium text-gray-600 mb-2"
>Check URL Status</label
>
<div class="flex flex-col sm:flex-row gap-3 sm:space-x-4">
<input
type="url"
id="urlInput"
placeholder="https://example.com"
class="w-full flex-1 rounded-lg border border-gray-200 px-4 py-2 focus:ring-1 focus:ring-gray-200 focus:border-gray-300 outline-none bg-gray-50 text-sm sm:text-base"
/>
<button
onclick="checkURL()"
class="w-full sm:w-auto bg-gray-100 text-gray-700 px-6 py-2 rounded-lg hover:bg-gray-200 transition-colors text-sm sm:text-base"
>
Check Status
</button>
</div>
</div>
</div>
</div>
<!-- Results Card -->
<div
id="resultsCard"
class="bg-white rounded-xl sm:rounded-2xl shadow-sm overflow-hidden hidden mt-4 sm:mt-6"
>
<!-- Status Header -->
<div
class="bg-gray-50 border-b border-gray-100 p-3 sm:p-4 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2 sm:gap-0"
>
<div class="flex items-center space-x-2">
<div id="statusDot" class="w-3 h-3 rounded-full bg-gray-300"></div>
<span
id="checkedUrl"
class="text-xs sm:text-sm text-gray-600 break-all"
>Checking...</span
>
</div>
<div class="text-xs sm:text-sm text-gray-500">
Last checked: <span id="lastChecked">Just now</span>
</div>
</div>
<!-- Metrics -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6 p-4 sm:p-6">
<!-- Latency -->
<div class="bg-gray-50 rounded-lg sm:rounded-xl p-4 sm:p-6">
<h3 class="text-xs sm:text-sm font-medium text-gray-600 mb-2">
Latency
</h3>
<div class="flex items-baseline">
<span
id="latencyValue"
class="text-2xl sm:text-4xl font-semibold text-gray-700"
>--</span
>
<span class="ml-2 text-sm text-gray-500">ms</span>
</div>
</div>
<!-- Status -->
<div class="bg-gray-50 rounded-lg sm:rounded-xl p-4 sm:p-6">
<h3 class="text-xs sm:text-sm font-medium text-gray-600 mb-2">
Site Status
</h3>
<div id="siteStatusDetails" class="space-y-2 text-sm"></div>
</div>
</div>
<!-- Additional Details -->
<div class="border-t border-gray-100 p-4 sm:p-6">
<div id="additionalInfo" class="space-y-3 sm:space-y-4 text-sm"></div>
</div>
<!-- History Section -->
<div class="border-t border-gray-100 p-4 sm:p-6">
<h3 class="text-xs sm:text-sm font-medium text-gray-700 mb-4">
Monitoring History
</h3>
<!-- History Charts -->
<div class="grid grid-cols-1 gap-4 sm:gap-6 mb-6">
<div
class="bg-gray-50 rounded-lg sm:rounded-xl p-3 sm:p-4 h-[250px] sm:h-[300px]"
>
<h4 class="text-xs sm:text-sm font-medium text-gray-600 mb-2">
Latency History
</h4>
<canvas id="latencyChart"></canvas>
</div>
<div
class="bg-gray-50 rounded-lg sm:rounded-xl p-3 sm:p-4 h-[250px] sm:h-[300px]"
>
<h4 class="text-xs sm:text-sm font-medium text-gray-600 mb-2">
Response Time History
</h4>
<canvas id="responseChart"></canvas>
</div>
</div>
<!-- History Table -->
<div class="mt-4 sm:mt-6">
<h4 class="text-xs sm:text-sm font-medium text-gray-600 mb-3">
Recent Checks
</h4>
<div class="overflow-x-auto -mx-4 sm:mx-0">
<div class="min-w-[640px] sm:min-w-full px-4 sm:px-0">
<table class="w-full">
<thead>
<tr class="bg-gray-50">
<th
class="px-3 sm:px-4 py-2 text-left text-xs font-medium text-gray-500"
>
Time
</th>
<th
class="px-3 sm:px-4 py-2 text-left text-xs font-medium text-gray-500"
>
Status
</th>
<th
class="px-3 sm:px-4 py-2 text-left text-xs font-medium text-gray-500"
>
Latency
</th>
<th
class="px-3 sm:px-4 py-2 text-left text-xs font-medium text-gray-500"
>
Response Time
</th>
<th
class="px-3 sm:px-4 py-2 text-left text-xs font-medium text-gray-500"
>
Code
</th>
<th
class="px-3 sm:px-4 py-2 text-left text-xs font-medium text-gray-500"
>
Error
</th>
</tr>
</thead>
<tbody
id="historyTableBody"
class="text-xs sm:text-sm"
></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer with adjusted positioning -->
<footer
class="bg-white/95 backdrop-blur-lg border-t border-black/[0.08] py-3 sm:py-4 mt-auto"
>
<div class="text-center text-xs sm:text-sm text-gray-500">
Created with ❤️ by
<a
href="https://github.com/jeffasante"
target="_blank"
rel="noopener noreferrer"
class="text-[#425b92] no-underline transition-opacity duration-200 hover:opacity-80"
>
jeffasante
</a>
</div>
</footer>
<script>
let currentChecker = null;
let history = new Map(); // Store history for each URL
let latencyChart = null;
let responseChart = null;
// Constants for chart management
const MAX_DATA_POINTS = 20; // Maximum number of data points to show
const CHART_UPDATE_INTERVAL = 5000; // Update interval in milliseconds
function initializeCharts() {
const commonOptions = {
responsive: true,
maintainAspectRatio: false,
animation: false,
plugins: {
legend: {
display: false,
},
},
scales: {
y: {
min: 0,
grace: "10%",
ticks: {
beginAtZero: true,
maxTicksLimit: 6,
callback: (value) => `${value}ms`,
},
grid: {
color: "rgba(0,0,0,0.1)",
drawBorder: false,
},
},
x: {
grid: {
display: false,
},
ticks: {
maxTicksLimit: 8,
maxRotation: 0,
minRotation: 0,
font: {
size: 10,
},
},
},
},
elements: {
line: {
tension: 0.3,
borderWidth: 2,
},
point: {
radius: 2,
hoverRadius: 4,
hitRadius: 20,
borderWidth: 2,
},
},
layout: {
padding: {
top: 10,
right: 10,
bottom: 10,
left: 10,
},
},
};
// Initialize charts directly
const latencyCtx = document.getElementById("latencyChart");
const responseCtx = document.getElementById("responseChart");
// Set fixed heights for chart containers
[latencyCtx, responseCtx].forEach((canvas) => {
const container = canvas.parentElement;
container.style.position = "relative";
container.style.height = "250px";
});
// Initialize Latency Chart
latencyChart = new Chart(latencyCtx, {
type: "line",
data: {
labels: [],
datasets: [
{
data: [],
borderColor: "rgb(147, 51, 234)",
backgroundColor: "rgba(147, 51, 234, 0.1)",
fill: true,
},
],
},
options: {
...commonOptions,
scales: {
...commonOptions.scales,
y: {
...commonOptions.scales.y,
title: {
display: true,
text: "Latency (ms)",
},
},
},
},
});
// Initialize Response Time Chart
responseChart = new Chart(responseCtx, {
type: "line",
data: {
labels: [],
datasets: [
{
data: [],
borderColor: "rgb(59, 130, 246)",
backgroundColor: "rgba(59, 130, 246, 0.1)",
fill: true,
},
],
},
options: {
...commonOptions,
scales: {
...commonOptions.scales,
y: {
...commonOptions.scales.y,
title: {
display: true,
text: "Response Time (ms)",
},
},
},
},
});
// Handle resize events
const resizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
const canvas = entry.target.querySelector("canvas");
if (canvas && canvas.chart) {
canvas.chart.resize();
}
});
});
// Observe the containers
[latencyCtx.parentElement, responseCtx.parentElement].forEach(
(container) => {
resizeObserver.observe(container);
}
);
}
function updateHistory(url, status, latency, siteStatus) {
if (!history.has(url)) {
history.set(url, []);
}
const urlHistory = history.get(url);
urlHistory.push({
timestamp: new Date(),
status,
latency,
siteStatus,
});
// Keep only last MAX_DATA_POINTS entries
if (urlHistory.length > MAX_DATA_POINTS) {
urlHistory.shift();
}
updateHistoryDisplay(url);
}
function updateHistoryDisplay(url) {
const urlHistory = history.get(url);
if (!urlHistory || urlHistory.length === 0) return;
// Get the data for charts
const labels = urlHistory.map((h) =>
h.timestamp.toLocaleTimeString("en-US", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
})
);
// Filter out null values and get valid data
const latencyData = urlHistory
.map((h) => h.latency || null)
.filter((val) => val !== null);
const responseData = urlHistory
.map((h) => h.siteStatus.responseTime || null)
.filter((val) => val !== null);
// Calculate reasonable min/max for Y axis
const maxLatency = Math.max(...latencyData, 100); // minimum 100ms range
const maxResponse = Math.max(...responseData, 100); // minimum 100ms range
// Update Latency Chart
latencyChart.data.labels = labels;
latencyChart.data.datasets[0].data = urlHistory.map(
(h) => h.latency || null
);
latencyChart.options.scales.y.max = maxLatency * 1.2; // Add 20% headroom
latencyChart.update();
// Update Response Chart
responseChart.data.labels = labels;
responseChart.data.datasets[0].data = urlHistory.map(
(h) => h.siteStatus.responseTime || null
);
responseChart.options.scales.y.max = maxResponse * 1.2; // Add 20% headroom
responseChart.update();
// Update table (show only last 10 entries)
const tableBody = document.getElementById("historyTableBody");
tableBody.innerHTML = urlHistory
.slice(-10)
.reverse()
.map(
(h) => `
<tr class="border-t border-gray-100">
<td class="px-4 py-2 text-sm text-gray-900">${h.timestamp.toLocaleTimeString()}</td>
<td class="px-4 py-2 text-sm">
<span class="inline-flex items-center">
<span class="w-2 h-2 rounded-full ${
h.siteStatus.isAlive ? "bg-green-500" : "bg-red-500"
} mr-2"></span>
${h.siteStatus.isAlive ? "Active" : "Failed"}
</span>
</td>
<td class="px-4 py-2 text-sm text-gray-900">${
h.latency || "--"
} ms</td>
<td class="px-4 py-2 text-sm text-gray-900">${
h.siteStatus.responseTime || "--"
} ms</td>
<td class="px-4 py-2 text-sm text-gray-900">${
h.siteStatus.statusCode || "--"
}</td>
<td class="px-4 py-2 text-sm text-red-500">${
h.siteStatus.error || "--"
}</td>
</tr>
`
)
.join("");
}
function updateUI(status, latency, siteStatus) {
// Show results card
document.getElementById("resultsCard").classList.remove("hidden");
// Update URL and status dot
const statusDot = document.getElementById("statusDot");
const checkedUrl = document.getElementById("checkedUrl");
statusDot.className = `w-3 h-3 rounded-full ${
status === "online" ? "bg-green-500" : "bg-red-500"
}`;
checkedUrl.textContent = currentChecker.options.siteURL;
// Update latency
const latencyValue = document.getElementById("latencyValue");
latencyValue.textContent = latency || "--";
// Update history
const url = currentChecker.options.siteURL;
updateHistory(url, status, latency, siteStatus);
// Update site status details
const siteStatusDetails = document.getElementById("siteStatusDetails");
siteStatusDetails.innerHTML = `
<div class="flex justify-between items-center">
<span class="text-sm text-gray-600">Status</span>
<span class="text-sm font-medium ${
siteStatus.isAlive ? "text-green-500" : "text-red-500"
}">
${siteStatus.isAlive ? "Active" : "Not Responding"}
</span>
</div>
<div class="flex justify-between items-center">
<span class="text-sm text-gray-600">Response Time</span>
<span class="text-sm font-medium text-gray-800">${
siteStatus.responseTime || "--"
} ms</span>
</div>
`;
// Update additional info
const additionalInfo = document.getElementById("additionalInfo");
additionalInfo.innerHTML = `
<div class="flex justify-between items-center">
<span class="text-sm text-gray-600">Status Code</span>
<span class="text-sm font-medium text-gray-800">${
siteStatus.statusCode || "--"
}</span>
</div>
${
siteStatus.error
? `
<div class="flex justify-between items-center">
<span class="text-sm text-gray-600">Error</span>
<span class="text-sm font-medium text-red-500">${siteStatus.error}</span>
</div>
`
: ""
}
<div class="flex justify-between items-center">
<span class="text-sm text-gray-600">Attempts</span>
<span class="text-sm font-medium text-gray-800">${
siteStatus.attempts
}</span>
</div>
<div class="flex justify-between items-center">
<span class="text-sm text-gray-600">Last Checked</span>
<span class="text-sm font-medium text-gray-800">${new Date(
siteStatus.lastChecked
).toLocaleTimeString()}</span>
</div>
`;
}
function checkURL() {
// Stop any existing checker
if (currentChecker) {
currentChecker.stop();
}
let url = document.getElementById("urlInput").value.trim();
if (!url) return;
// Add https:// if no protocol is specified
if (!/^https?:\/\//i.test(url)) {
url = "https://" + url;
}
try {
// Validate URL format
new URL(url);
} catch (e) {
console.error("Invalid URL format");
return;
}
// Initialize charts if not already done
if (!latencyChart) {
initializeCharts();
}
document.getElementById("resultsCard").classList.remove("hidden");
document.getElementById("statusDot").className =
"w-3 h-3 rounded-full bg-gray-300";
document.getElementById("checkedUrl").textContent = url;
document.getElementById("latencyValue").textContent = "--";
document.getElementById("siteStatusDetails").innerHTML =
'<div class="text-sm text-gray-500">Checking...</div>';
// Create new checker with validated URL
currentChecker = new NetworkStatusChecker({
siteURL: url,
checkSiteStatus: true,
pingInterval: 5000,
timeout: 5000,
retryAttempts: 2,
retryDelay: 1000,
onStatusChange: (status) => {
updateUI(status.status, status.latency, status.siteStatus);
},
onLatencyUpdate: (latency) => {
document.getElementById("latencyValue").textContent =
latency || "--";
},
onSiteStatusUpdate: (siteStatus) => {
updateUI("online", currentChecker.latency, siteStatus);
},
});
// Start checking
currentChecker.start();
}
document.getElementById("urlInput").addEventListener("keypress", (e) => {
if (e.key === "Enter") {
checkURL();
}
});
class NetworkStatusChecker {
constructor(options = {}) {
this.options = {
pingURL: options.pingURL || "https://www.google.com/favicon.ico", // Changed to more reliable endpoint
pingInterval: options.pingInterval || 10000,
timeout: options.timeout || 5000,
retryAttempts: options.retryAttempts || 2,
retryDelay: options.retryDelay || 1000,
onStatusChange: options.onStatusChange || (() => {}),
onLatencyUpdate: options.onLatencyUpdate || (() => {}),
onSiteStatusUpdate: options.onSiteStatusUpdate || (() => {}),
checkSiteStatus: options.checkSiteStatus || false,
siteURL: options.siteURL || window.location.origin,
};
this.isOnline = navigator.onLine;
this.latency = null;
this.intervalId = null;
this.lastPingTime = null;
this.siteStatus = {
isAlive: null,
statusCode: null,
responseTime: null,
lastChecked: null,
error: null,
attempts: 0,
};
// Bind methods
this.checkConnection = this.checkConnection.bind(this);
this.handleOnline = this.handleOnline.bind(this);
this.handleOffline = this.handleOffline.bind(this);
this.measureLatency = this.measureLatency.bind(this);
this.checkSiteHealth = this.checkSiteHealth.bind(this);
// Initialize event listeners
this.initializeEventListeners();
}
initializeEventListeners() {
window.addEventListener("online", this.handleOnline);
window.addEventListener("offline", this.handleOffline);
}
handleOnline() {
this.isOnline = true;
this.options.onStatusChange({
status: "online",
latency: this.latency,
siteStatus: this.siteStatus,
});
}
handleOffline() {
this.isOnline = false;
this.latency = null;
this.siteStatus.isAlive = false;
this.siteStatus.error = "Device is offline";
this.options.onStatusChange({
status: "offline",
latency: null,
siteStatus: this.siteStatus,
});
}
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async measureLatency() {
if (!this.isOnline) return null;
this.lastPingTime = Date.now();
return new Promise((resolve) => {
const start = performance.now();
const img = new Image();
const timeout = setTimeout(() => {
img.src = "";
resolve(null);
}, this.options.timeout);
img.onload = () => {
clearTimeout(timeout);
this.latency = Math.round(performance.now() - start);
resolve(this.latency);
};
img.onerror = () => {
clearTimeout(timeout);
this.latency = null;
resolve(null);
};
img.src = "https://www.google.com/favicon.ico?" + Date.now();
});
}
async checkSiteHealth(attemptNumber = 1) {
if (!this.isOnline || !this.options.checkSiteStatus) return;
try {
const startTime = performance.now();
// Always use no-cors mode and GET method for broader compatibility
const fetchOptions = {
cache: "no-store",
mode: "no-cors",
method: "GET",
timeout: this.options.timeout,
credentials: "omit",
};
const response = await fetch(this.options.siteURL, fetchOptions);
const endTime = performance.now();
// With no-cors, we won't get status details but can confirm site is reachable
this.siteStatus = {
isAlive: true, // If fetch succeeds, site is reachable
statusCode: "OK", // Can't get actual status code in no-cors mode
responseTime: Math.round(endTime - startTime),
lastChecked: new Date().toISOString(),
error: null,
attempts: attemptNumber,
};
} catch (error) {
// If we haven't exceeded retry attempts, try again
if (attemptNumber < this.options.retryAttempts) {
await this.sleep(this.options.retryDelay);
return this.checkSiteHealth(attemptNumber + 1);
}
this.siteStatus = {
isAlive: false,
statusCode: null,
responseTime: null,
lastChecked: new Date().toISOString(),
error: this.getErrorMessage(error),
attempts: attemptNumber,
};
}
this.options.onSiteStatusUpdate(this.siteStatus);
return this.siteStatus;
}
getErrorMessage(error) {
if (
error.name === "TypeError" &&
error.message.includes("Failed to fetch")
) {
return "Site unreachable - network error";
} else if (error.name === "AbortError") {
return "Request timed out";
} else if (error.message.includes("CORS")) {
return "Site reachable but blocked by CORS";
}
return `Connection error: ${error.message}`;
}
getStatusCodeMessage(status) {
const statusMessages = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
};
return statusMessages[status] || `HTTP Error ${status}`;
}
async checkConnection() {
try {
const latency = await this.measureLatency();
this.options.onLatencyUpdate(latency);
if (this.options.checkSiteStatus) {
await this.checkSiteHealth();
}
} catch (error) {
console.error("Network check failed:", error);
}
}
start() {
this.checkConnection();
this.intervalId = setInterval(
this.checkConnection,
this.options.pingInterval
);
return this;
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
window.removeEventListener("online", this.handleOnline);
window.removeEventListener("offline", this.handleOffline);
return this;
}
getStatus() {
return {
online: this.isOnline,
latency: this.latency,
lastChecked: this.lastPingTime,
siteStatus: this.siteStatus,
};
}
}
// Example usage with better error handling:
const networkChecker = new NetworkStatusChecker({
siteURL: "https://google.com",
checkSiteStatus: true,
pingInterval: 30000,
timeout: 5000,
retryAttempts: 2, // Will try up to 2 additional times if first attempt fails
retryDelay: 1000, // Wait 1 second between retries
onStatusChange: (status) => {
console.log("Network status changed:", status);
},
onLatencyUpdate: (latency) => {
if (latency === null) {
console.warn("Latency check failed");
} else {
console.log("Current latency:", latency, "ms");
}
},
onSiteStatusUpdate: (siteStatus) => {
console.log("Site status:", siteStatus);
if (!siteStatus.isAlive) {
console.error(
"Site check failed after",
siteStatus.attempts,
"attempts:",
siteStatus.error
);
}
},
});
// networkChecker.start();
</script>
</body>
</html>