April 10, 2019
How to Check Whether User Online/Offline in Javascript
This is a very small and basic tutorial about usage of navigator api to check if user is online or offline.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div id="container"> <span></span> </div> <script src="script.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const status = window.navigator.onLine; if(status) online() else offline() window.addEventListener('online', online); window.addEventListener('offline', offline); function online(){ document.getElementById('container').style.backgroundColor = 'green'; document.querySelector('span').textContent = 'Online'; } function offline(){ document.getElementById('container').style.backgroundColor = 'red'; document.querySelector('span').textContent = 'Offline'; } |
1 2 3 4 5 6 |
#container { width: 100%; border: 1px solid black; text-align: center; color: #fff; } |