proyectoscorpion
Digital Supply Chain Strategist
2
MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1
300 XP
In this tutorial, you will learn how to Create a Connection Checker w/ Popup Message for web applications or websites using JavaScript and Bootstrap v5 Framework. This tutorial's main purpose is to provide the IT/CS students and self-learners/beginners with a reference to learning how to detect internet connection changes on the client side using the JavaScript Navigator API. Here, snippets are also included and a simple working web application source code zip file is provided and free to download.
Why do we need to Implement Internet Connection Checker in websites or web applications?
Implementing Checking/Detecting Internet Connections in websites or web applications is not a must or required. Though browsers automatically give a message or load an internet connection lost page when the client's connection has lost or failed, developers still implement this feature with their websites or web applications for some instance such as to prevent the client submit the form and wait till the connection has restored or in any case that they want to notify their clients about their internet connection due to the fact that the process or action will or might fail.
How to create a Connection Checker w/ Popup Message?
JavaScript comes with a method or instance property called Navigator.onLine. This is one of the instances properties of the JavaScript Navigator API. The said instance returns a boolean value of the browser's online status. If true
, the internet connection status of the browser is online otherwise false
. Read more about the Navigator.onLine browser compatibility at https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#browser_compatibility.
Alongside the JavaScript's Navigator.onLine method, the Bootstrap Framework and Google Material Icons are also useful for creating a popup message more presentable and easier to make. Then, using the setInterval() function/method of JS, we can loop a custom function that will check the connection status on the client side from time to time.
Example
Assuming that we have the following website page interface script below.
In the sample snippet above, you can see the Connection Popup Message Container below the '<!-- Connection Popup Message -->
' comment and the included script named connection-checker.js is the file that contains the JavaScript codes for checking the connection, displaying the notification or message for connection status changes, and loop the connection checker function on the client side.
connection-checker.js
And here's the additional CSS script, for the design of the connection message popup container/card.
As the result, when the user has browsed the website and suddenly loses their internet connection. The offline message will be shown at the bottom-left of the page window like the following image.
And if the connection was restored, it would be like the following.
You can download the source code that I created for this tutorial that can give you an actual demonstration using the code I have provided above. The download button is located below this tutorial's content.
DEMO VIDEO
There you go! I hope this Checking Internet Connection using JavaScript Navigator API Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding =)
Download
Why do we need to Implement Internet Connection Checker in websites or web applications?
Implementing Checking/Detecting Internet Connections in websites or web applications is not a must or required. Though browsers automatically give a message or load an internet connection lost page when the client's connection has lost or failed, developers still implement this feature with their websites or web applications for some instance such as to prevent the client submit the form and wait till the connection has restored or in any case that they want to notify their clients about their internet connection due to the fact that the process or action will or might fail.
How to create a Connection Checker w/ Popup Message?
JavaScript comes with a method or instance property called Navigator.onLine. This is one of the instances properties of the JavaScript Navigator API. The said instance returns a boolean value of the browser's online status. If true
, the internet connection status of the browser is online otherwise false
. Read more about the Navigator.onLine browser compatibility at https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#browser_compatibility.
Alongside the JavaScript's Navigator.onLine method, the Bootstrap Framework and Google Material Icons are also useful for creating a popup message more presentable and easier to make. Then, using the setInterval() function/method of JS, we can loop a custom function that will check the connection status on the client side from time to time.
Example
Assuming that we have the following website page interface script below.
- <!DOCTYPE html>
- <html
lang
=
"en"
>
- <head
>
- <meta
charset
=
"UTF-8"
>
- <meta
http-equiv
=
"X-UA-Compatible"
content
=
"IE=edge"
>
- <meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
- <title
>
JS - Check Internet Connection</
title
>
- <link
rel
=
"stylesheet"
href
=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
integrity=
"sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
crossorigin=
"anonymous"
referrerpolicy=
"no-referrer"
/
>
- <link
rel
=
"stylesheet"
href
=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity=
"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"
crossorigin=
"anonymous"
>
- <link
rel
=
"stylesheet"
href
=
"assets/css/styles.css"
>
- <!-- Google Icons -->
- <link
rel
=
"stylesheet"
href
=
"https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200"
/
>
- <link
rel
=
"stylesheet"
href
=
"https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,200,0,0"
/
>
- <!-- Google Icons -->
- <script
src
=
"https://code.jquery.com/jquery-3.6.1.js"
integrity=
"sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin=
"anonymous"
></
script
>
- <script
src
=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity=
"sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin=
"anonymous"
></
script
>
- <script
src
=
"assets/js/script.js"
></
script
>
- <style
>
- .material-symbols-outlined {
- font-variation-settings:
- 'FILL' 0,
- 'wght' 200,
- 'GRAD' 0,
- 'opsz' 48
- }
- </
style
>
- </
head
>
- <body
>
- <!-- Connection Popup Message -->
- <div
class
=
"position-fixed bottom-0 start-0 rounded-0 pb-3 ps-3"
id
=
"connectionMessage"
>
- <div
class
=
"card rounded-0 shadow"
>
- <div
class
=
"card-body"
>
- <div
class
=
"container-fluid"
>
- <div
class
=
"d-flex align-items-center"
>
- <div
class
=
"col-auto px-3 cm-icon-field"
>
- <span
class
=
"material-symbols-outlined"
>
wifi_off</
span
>
- </
div
>
- <div
class
=
"col-auto px-2 flex-shrink-1 flex-grow-1 cm-text-field"
>
Internet Connection has been restored.</
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- <!-- End of Connection Popup Message -->
- <main>
- <nav
class
=
"navbar navbar-expand-lg navbar-dark bg-gradient"
>
- <div
class
=
"container"
>
- <a
class
=
"navbar-brand"
href
=
"./"
>
JS - Check Internet Connection</
a
>
- <a
href
=
"https://sourcecodester.com"
class
=
"text-light fw-bolder h6 text-decoration-none"
target
=
"_blank"
>
SourceCodester</
a
>
- </
div
>
- </
nav
>
- <div
id
=
"main-wrapper"
>
- <script
>
- start_loader()
- </
script
>
- <div
class
=
"container px-5 my-3"
>
- <h1
class
=
"text-center fw-bolder"
>
Sample Site Content</
h1
>
- <hr
>
- <p
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc convallis tortor at molestie tempor. Donec facilisis scelerisque nibh non venenatis. Sed commodo ante cursus, scelerisque tortor vel, vulputate dolor. Donec eget ullamcorper dolor, et venenatis urna. Duis justo arcu, scelerisque in aliquet quis, euismod ac ex. Nullam justo felis, sollicitudin et hendrerit faucibus, maximus at ex. Vivamus viverra varius odio non suscipit. Nulla sit amet lorem diam. Curabitur vel quam felis. Maecenas lacus lectus, feugiat ac mollis id, pharetra maximus dolor. Nam imperdiet, lectus et venenatis vulputate, nisi dolor eleifend nunc, gravida vestibulum quam velit eu metus.</
p
>
- <p
>
Cras dictum eleifend lacus, eget mattis turpis faucibus in. Mauris ac maximus magna. Phasellus facilisis, felis aliquet feugiat tincidunt, felis tellus molestie sapien, aliquam congue sapien est vel libero. In placerat pellentesque congue. Aenean rutrum consequat magna, et viverra lectus. Proin leo justo, efficitur ac interdum sed, placerat nec nunc. Aliquam erat volutpat. Vestibulum non justo vehicula, consectetur odio a, ultricies mauris. Quisque quis ex vehicula ante pellentesque molestie eu varius tortor. Praesent sodales diam vel pellentesque feugiat. Nunc quis sapien odio. Proin est enim, convallis non iaculis non, tempor vel tortor. Mauris varius quis neque id auctor.</
p
>
- </
div
>
- </
div
>
- <footer
class
=
"bg-gradient bg-light shadow-top py-4 col-auto"
>
- <div
class
=
""
>
- <div
class
=
"text-center"
>
- All Rights Reserved ©
<span
id
=
"dt-year"
></
span
>
| <span
class
=
"text-muted"
>
JS - Check Internet Connection</
span
>
- </
div
>
- <div
class
=
"text-center"
>
- <a
href
=
"mailto:[email protected]"
class
=
"text-decoration-none text-success"
>
[email protected]</
a
>
- </
div
>
- </
div
>
- </
footer
>
- </
main>
- <script
src
=
"assets/js/connection-checker.js"
></
script
>
- </
body
>
- </
html
>
In the sample snippet above, you can see the Connection Popup Message Container below the '<!-- Connection Popup Message -->
' comment and the included script named connection-checker.js is the file that contains the JavaScript codes for checking the connection, displaying the notification or message for connection status changes, and loop the connection checker function on the client side.
connection-checker.js
- /** ConnectionStatus Variables */
- var
connectionStatus,
currentConnectionStatus;
- /** Connection Icons */
- const
connectionIcons =
{
- online :
`<
span class
=
"material-symbols-outlined text-muted"
>
wifi</
span>
`,
- offline :
`<
span class
=
"material-symbols-outlined text-muted"
>
wifi_off</
span>
`,
- }
- /** Connection Text Message */
- const
connectionMsg =
{
- online :
`Internet Connection is Restored`,
- offline :
`Internet Connection Lost/
Failed`,
- }
- /** Connection Popup Message Container Node/Element */
- const
connectionMsgContainer =
document.getElementById
(
'connectionMessage'
)
- /**Checing Internel Connection Function */
- window.checkInternetConnection
=
function
(
)
{
- if
(
navigator.onLine
)
{
- /** Connection online */
- connectionStatus =
"online"
- }
else
{
- /** Connection offline */
- connectionStatus =
"offline"
- }
- /** Check if connection has changes compare from previous status */
- if
(
currentConnectionStatus !==
undefined
&&
currentConnectionStatus !=
connectionStatus)
{
- /** Removing the added class */
- if
(
connectionMsgContainer.querySelector
(
'.card'
)
.classList
.contains
(
'online'
)
)
- connectionMsgContainer.querySelector
(
'.card'
)
.classList
.remove
(
'online'
)
;
- if
(
connectionMsgContainer.querySelector
(
'.card'
)
.classList
.contains
(
'offline'
)
)
- connectionMsgContainer.querySelector
(
'.card'
)
.classList
.remove
(
'offline'
)
;
- if
(
connectionStatus ==
'online'
)
{
- /** If connecion stutus has change to online */
- connectionMsgContainer.querySelector
(
'.card'
)
.classList
.add
(
'online'
)
- connectionMsgContainer.querySelector
(
'.cm-icon-field'
)
.innerHTML
=
connectionIcons.online
- connectionMsgContainer.querySelector
(
'.cm-text-field'
)
.innerHTML
=
connectionMsg.online
- connectionMsgContainer.style
.opacity
=
1
- setTimeout(
(
)
=>
{
- connectionMsgContainer.style
.opacity
=
0
- }
,
5000
)
- }
else
{
- /** If connecion stutus has change to offline */
- connectionMsgContainer.querySelector
(
'.card'
)
.classList
.add
(
'offline'
)
- connectionMsgContainer.querySelector
(
'.cm-icon-field'
)
.innerHTML
=
connectionIcons.offline
- connectionMsgContainer.querySelector
(
'.cm-text-field'
)
.innerHTML
=
connectionMsg.offline
- connectionMsgContainer.style
.opacity
=
1
- }
- }
- /** Update Current Connection Status */
- currentConnectionStatus =
connectionStatus;
- }
- if
(
!!
navigator)
{
- /** Loop Internet Connection Checking Function every 1 second */
- setInterval(
(
)
=>
{
- checkInternetConnection(
)
- }
,
1000
)
- }
And here's the additional CSS script, for the design of the connection message popup container/card.
- /** Internet Connection */
- #connectionMessage
{
- opacity
:
0
;
- transition
:
opacity .3s
cubic-bezier
(
0.4
,
0
,
1
,
1
)
;
- }
- #connectionMessage
.card
.online{
- border
:
1px
solid
var
(
--bs-teal
)
!important;
- }
- #connectionMessage
.card
.offline{
- border
:
1px
solid
#dc354540
!important;
- }
- #connectionMessage
.card
.online
.material-symbols-outlined{
- color
:
var
(
--bs-teal
)
;
- }
- #connectionMessage
.card
.offline
.material-symbols-outlined
,
- #connectionMessage
.card
.offline
.cm-text-field{
- color
:
var
(
--bs-gray-700
)
;
- }
- #connectionMessage
.card
.online
.cm-text-field{
- color
:
var
(
--bs-gray-dark
)
;
- }
As the result, when the user has browsed the website and suddenly loses their internet connection. The offline message will be shown at the bottom-left of the page window like the following image.
And if the connection was restored, it would be like the following.
You can download the source code that I created for this tutorial that can give you an actual demonstration using the code I have provided above. The download button is located below this tutorial's content.
DEMO VIDEO
There you go! I hope this Checking Internet Connection using JavaScript Navigator API Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding =)
Download
You must upgrade your account or reply in the thread to view the hidden content.