Ensuring Connectivity: A Guide on Checking Internet Connection with JavaScript

This tutorial delves into techniques for verifying internet connectivity in a web application using JavaScript. Its purpose is to offer students and beginners a valuable reference to enhance their knowledge and skills in developing web applications with JavaScript. Throughout this tutorial, I'll be presenting code snippets to illustrate our objectives on this website.

Why is it crucial to guarantee Internet Connection in Web Applications?

Securing a consistent internet connection in web applications is vital for various reasons, particularly in sustaining seamless functionality, delivering real-time updates, and ensuring a responsive user experience. A dependable internet connection becomes essential for applications that heavily rely on continuous data exchange with servers, ensuring users can access and interact with the application without interruptions.

JavaScript offers various valuable built-in event listeners, including the click and input event listeners. Several of these event listeners prove exceptionally useful in achieving the objective of ensuring internet connection in our tutorial. To implement this in our web application, we can introduce a feature that notifies end-users about their internet connection status, leveraging the `offline` and `online` event listeners.

In JavaScript, the Offline and Online Event Listeners serve as mechanisms enabling developers to detect changes in the network connectivity status of a web application or device. These events empower developers to dynamically respond to the online or offline state. The `online` event triggers when the device or browser establishes an internet connection, while the `offline` event triggers when the device or browser loses internet connection.

To gain a deeper understanding of utilizing the `online` and `offline` event listeners, let's construct a simple web application featuring notifications for when the device or browser loses and regains internet connection.

Below is the source code script for the simple web application:

CSS

Generate a new CSS file and copy/paste the following CSS script. This file encapsulates the code for customizing the design of various elements of the application. Save the file as `style.css`.

  1. @import url('https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap');
  2. * {
  3. font-family: 'Ubuntu', sans-serif;
  4. }
  5.  
  6. html, body{
  7. background-color: #0093E9;
  8. background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);
  9. height: 100%;
  10. max-height: 100%;
  11. width: 100%;
  12. max-width: 100%;
  13. overflow: auto;
  14. margin: unset;
  15. }
  16. body{
  17. display: flex;
  18. flex-flow:column wrap;
  19. align-items:center;
  20. justify-content:center;
  21. }
  22.  
  23. #main-wrapper{
  24. width: 100%;
  25. max-width: 500px;
  26. padding: .75rem .75rem;
  27. }
  28.  
  29. #page-title{
  30. font-size: 1.9rem;
  31. font-weight: bold;
  32. color:#fff;
  33. text-shadow: 0px 3px 5px #00000065;
  34. text-align: center;
  35. }
  36.  
  37. .flash-message{
  38. position: fixed;
  39. top:10px;
  40. right:10px;
  41. width: 100%;
  42. max-width: 380px;
  43. background-color: #fff;
  44. box-shadow: 0px 3px 7px #00000077;
  45. padding: .35em .35em;
  46. z-index: 999;
  47. display: flex;
  48. flex-flow: row wrap;
  49. align-items:center;
  50. justify-content:center;
  51. border-left: 5px solid #8d8d8d;
  52. }
  53.  
  54. .flash-message>div:nth-child(1){
  55. width: 50px;
  56. height: 50px;
  57. display: flex;
  58. justify-content: center;
  59. align-items: center;
  60. }
  61. .flash-message>div:nth-child(2){
  62. flex-grow:1;
  63. }
  64. .flash-message.success{
  65. border-left-color: #29af29;
  66. }
  67. .flash-message.success .msg-icon > svg{
  68. color: #29af29;
  69. }
  70.  
  71. .flash-message.danger{
  72. border-left-color: #f34646;
  73. }
  74. .flash-message.danger .msg-icon > svg{
  75. color: #3a3a3a;
  76. }
  77. #predisplay-icons{
  78. display: none;
  79. }

HTML

Next, create a new HTML file and save it as `index.html`. This file encompasses the User Interface elements for the simple web page.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <title>Check Internet Connection</title>
  6. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  7.  
  8. <link rel="stylesheet" href="style.css">
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/js/all.min.js" integrity="sha512-GWzVrcGlo0TxTRvz9ttioyYJ+Wwk9Ck0G81D+eO63BaqHaJ3YZX9wuqjwgfcV/MrB2PhaVX9DkYVhbFpStnqpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10. </head>
  11. <div id="main-wrapper">
  12. <div id="page-title">Checking Internet Connection using JavaScript</div>
  13. </div>
  14. <script src="script.js"></script>
  15. </body>
  16. </html>

JavaScript

Lastly, craft the JavaScript file named `script.js`. This file houses the functionality that notifies users about their internet connection state changes. The script encompasses both the `online` and `offline` events.

  1. let isOnline = true
  2. // Offline Internet Connection Icon
  3. let netOffIcon = '<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-wifi-off" height="30px" width="30px"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M10.706 3.294A12.545 12.545 0 0 0 8 3C5.259 3 2.723 3.882.663 5.379a.485.485 0 0 0-.048.736.518.518 0 0 0 .668.05A11.448 11.448 0 0 1 8 4c.63 0 1.249.05 1.852.148l.854-.854zM8 6c-1.905 0-3.68.56-5.166 1.526a.48.48 0 0 0-.063.745.525.525 0 0 0 .652.065 8.448 8.448 0 0 1 3.51-1.27L8 6zm2.596 1.404.785-.785c.63.24 1.227.545 1.785.907a.482.482 0 0 1 .063.745.525.525 0 0 1-.652.065 8.462 8.462 0 0 0-1.98-.932zM8 10l.933-.933a6.455 6.455 0 0 1 2.013.637c.285.145.326.524.1.75l-.015.015a.532.532 0 0 1-.611.09A5.478 5.478 0 0 0 8 10zm4.905-4.905.747-.747c.59.3 1.153.645 1.685 1.03a.485.485 0 0 1 .047.737.518.518 0 0 1-.668.05 11.493 11.493 0 0 0-1.811-1.07zM9.02 11.78c.238.14.236.464.04.66l-.707.706a.5.5 0 0 1-.707 0l-.707-.707c-.195-.195-.197-.518.04-.66A1.99 1.99 0 0 1 8 11.5c.374 0 .723.102 1.021.28zm4.355-9.905a.53.53 0 0 1 .75.75l-10.75 10.75a.53.53 0 0 1-.75-.75l10.75-10.75z"></path> </g></svg>';
  4.  
  5. // Online Internet Connection Icon
  6. let netOnIcon = '<svg fill="currentColor" height="30px" width="30px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 494.45 494.45" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <g> <g> <path d="M395.225,277.325c-6.8,0-13.5-2.6-18.7-7.8c-71.4-71.3-187.4-71.3-258.8,0c-10.3,10.3-27.1,10.3-37.4,0 s-10.3-27.1,0-37.4c92-92,241.6-92,333.6,0c10.3,10.3,10.3,27.1,0,37.4C408.725,274.725,401.925,277.325,395.225,277.325z"></path> </g> <g> <path d="M323.625,348.825c-6.8,0-13.5-2.6-18.7-7.8c-15.4-15.4-36-23.9-57.8-23.9s-42.4,8.5-57.8,23.9 c-10.3,10.3-27.1,10.3-37.4,0c-10.3-10.3-10.3-27.1,0-37.4c25.4-25.4,59.2-39.4,95.2-39.4s69.8,14,95.2,39.5 c10.3,10.3,10.3,27.1,0,37.4C337.225,346.225,330.425,348.825,323.625,348.825z"></path> </g> <g> <circle cx="247.125" cy="398.925" r="35.3"></circle> </g> <g> <path d="M467.925,204.625c-6.8,0-13.5-2.6-18.7-7.8c-111.5-111.4-292.7-111.4-404.1,0c-10.3,10.3-27.1,10.3-37.4,0 s-10.3-27.1,0-37.4c64-64,149-99.2,239.5-99.2s175.5,35.2,239.5,99.2c10.3,10.3,10.3,27.1,0,37.4 C481.425,202.025,474.625,204.625,467.925,204.625z"></path> </g> </g> </g> </g></svg>';
  7.  
  8. // Connection Message Container
  9. const flashMsg = document.createElement('div');
  10. flashMsg.classList.add('flash-message');
  11.  
  12. let flashMsgText = `
  13. <div class="msg-icon">
  14. </div>
  15. <div class="msg-txt"></div>
  16. `;
  17.  
  18.  
  19. /**
  20.   * Display Message when Internet Connection Lost
  21.   */
  22. window.addEventListener('offline', function(){
  23. // Remove current Notification if do exists
  24. if(document.querySelectorAll('.flash-message').length > 0){
  25. document.querySelector('.flash-message').remove()
  26. }
  27.  
  28. // Clone Notification Container
  29. const notif = flashMsg.cloneNode()
  30. // Notification Content
  31. notif.innerHTML = flashMsgText
  32. // Notification Type
  33. notif.classList.add('danger')
  34. // Notification Icon
  35. notif.querySelector('.msg-icon').innerHTML = netOffIcon
  36. // Notification Text Content
  37. notif.querySelector('.msg-txt').innerText = `Internet connection lost!`;
  38. document.body.appendChild(notif)
  39.  
  40. // Update Connection Status
  41. isOnline = false;
  42. })
  43.  
  44. /**
  45.   * Display Message when Internet Connection Restored
  46.   */
  47. window.addEventListener('online', function(){
  48. // Remove current Notification if do exists
  49. if(document.querySelectorAll('.flash-message').length > 0){
  50. document.querySelector('.flash-message').remove()
  51. }
  52.  
  53. if(!isOnline){
  54. // Clone Notification Container
  55. const notif = flashMsg.cloneNode()
  56. // Notification Content
  57. notif.innerHTML = flashMsgText
  58. // Notification Type
  59. notif.classList.add('success')
  60. // Notification Icon
  61. notif.querySelector('.msg-icon').innerHTML = netOnIcon
  62. // Notification Text Content
  63. notif.querySelector('.msg-txt').innerText = `Internet connection restored!`;
  64. document.body.appendChild(notif)
  65.  
  66. // Update Connection Status
  67. isOnline = true;
  68.  
  69. // Automatically Remove the Notification after 5 seconds
  70. setTimeout(function(){
  71. notif.remove()
  72. }, 5000)
  73. }
  74.  
  75. })
  76.  

Result

Explore the snapshots below showcasing the results of the provided source code:

Page UI

Ensuring Internet Connection in JavaScript

When Connection is Lost

Ensuring Internet Connection in JavaScript

When Connection Restored

Ensuring Internet Connection in JavaScript

There you have it! The complete source code zip file is available for free on this website. Feel free to download and customize it by clicking the Download button below this tutorial content.

Additionally, consider exploring or downloading the following:

And there you have it! I trust this Guide on Checking Internet Connection with JavaScript proves helpful for your needs and will be a valuable resource for your future web application projects. Delve deeper into this website for an array of Tutorials, Free Source Codes, and Articles spanning various programming languages.

Happy Coding =)

Add new comment