Checking Internet Connection using JavaScript Navigator API Tutorial

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.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>JS - Check Internet Connection</title>
  7.     <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" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.     <link rel="stylesheet" href="assets/css/styles.css">
  10.  
  11.     <!-- Google Icons -->
  12.     <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  13.     <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,200,0,0" />
  14.     <!-- Google Icons -->
  15.     <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  16.     <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>
  17.  
  18.     <script src="assets/js/script.js"></script>
  19.     <style>
  20.         .material-symbols-outlined {
  21.             font-variation-settings:
  22.             'FILL' 0,
  23.             'wght' 200,
  24.             'GRAD' 0,
  25.             'opsz' 48
  26.         }
  27.     </style>
  28. </head>
  29.     <!-- Connection Popup Message -->
  30.     <div class="position-fixed bottom-0 start-0 rounded-0 pb-3 ps-3" id="connectionMessage" >
  31.         <div class="card rounded-0 shadow">
  32.             <div class="card-body">
  33.                 <div class="container-fluid">
  34.                     <div class="d-flex align-items-center">
  35.                         <div class="col-auto px-3 cm-icon-field">
  36.                             <span class="material-symbols-outlined">wifi_off</span>
  37.                         </div>
  38.                         <div class="col-auto px-2 flex-shrink-1 flex-grow-1 cm-text-field">Internet Connection has been restored.</div>
  39.                     </div>
  40.                 </div>
  41.             </div>
  42.         </div>
  43.     </div>
  44.     <!-- End of Connection Popup Message -->
  45.     <main>
  46.         <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  47.             <div class="container">
  48.                 <a class="navbar-brand" href="./">JS - Check Internet Connection</a>
  49.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  50.             </div>
  51.         </nav>
  52.         <div id="main-wrapper">
  53.             <script>
  54.                 start_loader()
  55.             </script>
  56.             <div class="container px-5 my-3">
  57.                     <h1 class="text-center fw-bolder">Sample Site Content</h1>
  58.                     <hr>
  59.                     <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>
  60.                     <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>
  61.             </div>
  62.         </div>
  63.         <footer class="bg-gradient bg-light shadow-top py-4 col-auto">
  64.             <div class="">
  65.                 <div class="text-center">
  66.                     All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">JS - Check Internet Connection</span>
  67.                 </div>
  68.                 <div class="text-center">
  69.                     <a href="mailto:[email protected]" class="text-decoration-none text-success">[email protected]</a>
  70.                 </div>
  71.             </div>
  72.         </footer>
  73.     </main>
  74.     <script src="assets/js/connection-checker.js"></script>
  75.    
  76. </body>
  77. </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

  1. /** ConnectionStatus Variables */
  2. var connectionStatus, currentConnectionStatus;
  3. /** Connection Icons */
  4. const connectionIcons = {
  5.     online : `<span class="material-symbols-outlined text-muted">wifi</span>`,
  6.     offline : `<span class="material-symbols-outlined text-muted">wifi_off</span>`,
  7. }
  8. /** Connection Text Message */
  9. const connectionMsg = {
  10.     online : `Internet Connection is Restored`,
  11.     offline : `Internet Connection Lost/Failed`,
  12. }
  13. /** Connection Popup Message Container Node/Element */
  14. const connectionMsgContainer = document.getElementById('connectionMessage')
  15.  
  16. /**Checing Internel Connection Function */
  17. window.checkInternetConnection = function(){
  18.     if(navigator.onLine){
  19.         /** Connection online */
  20.         connectionStatus = "online"
  21.     }else{
  22.         /** Connection offline */
  23.         connectionStatus = "offline"
  24.     }
  25.     /** Check if connection has changes compare from previous status  */
  26.     if(currentConnectionStatus !== undefined && currentConnectionStatus != connectionStatus){
  27.         /** Removing the added class */
  28.         if(connectionMsgContainer.querySelector('.card').classList.contains('online'))
  29.             connectionMsgContainer.querySelector('.card').classList.remove('online');
  30.         if(connectionMsgContainer.querySelector('.card').classList.contains('offline'))
  31.             connectionMsgContainer.querySelector('.card').classList.remove('offline');
  32.  
  33.         if(connectionStatus == 'online'){
  34.             /** If connecion stutus has change to online */
  35.             connectionMsgContainer.querySelector('.card').classList.add('online')
  36.             connectionMsgContainer.querySelector('.cm-icon-field').innerHTML = connectionIcons.online
  37.             connectionMsgContainer.querySelector('.cm-text-field').innerHTML = connectionMsg.online
  38.             connectionMsgContainer.style.opacity = 1
  39.             setTimeout(()=>{
  40.                 connectionMsgContainer.style.opacity = 0
  41.             },5000)
  42.         }else{
  43.             /** If connecion stutus has change to offline */
  44.             connectionMsgContainer.querySelector('.card').classList.add('offline')
  45.             connectionMsgContainer.querySelector('.cm-icon-field').innerHTML = connectionIcons.offline
  46.             connectionMsgContainer.querySelector('.cm-text-field').innerHTML = connectionMsg.offline
  47.             connectionMsgContainer.style.opacity = 1
  48.         }
  49.     }
  50.     /** Update Current Connection Status */
  51.     currentConnectionStatus = connectionStatus;
  52. }
  53.  
  54. if(!!navigator){
  55.     /** Loop Internet Connection Checking Function every 1 second */
  56.     setInterval(()=>{
  57.         checkInternetConnection()
  58.     }, 1000)
  59. }

And here's the additional CSS script, for the design of the connection message popup container/card.

  1. /** Internet Connection */
  2. #connectionMessage{
  3.     opacity: 0;
  4.     transition: opacity .3s cubic-bezier(0.4, 0, 1, 1);
  5. }
  6. #connectionMessage .card.online{
  7.     border: 1px solid var(--bs-teal) !important;
  8. }
  9. #connectionMessage .card.offline{
  10.     border: 1px solid #dc354540 !important;
  11. }
  12. #connectionMessage .card.online .material-symbols-outlined{
  13.     color: var(--bs-teal);
  14. }
  15. #connectionMessage .card.offline .material-symbols-outlined,
  16. #connectionMessage .card.offline .cm-text-field{
  17.     color: var(--bs-gray-700);
  18. }
  19. #connectionMessage .card.online .cm-text-field{
  20.     color: var(--bs-gray-dark);
  21. }

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.

Checking Internet Connection Status using JavaScript

And if the connection was restored, it would be like the following.

Checking Internet Connection Status using JavaScript

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 =)

Add new comment