Check Internet Connection in HTML 5 using JavaScript
This blog helps you to determine the internet
connectivity for your web application and detects whether you are online or
offline using JavaScript.
It helps the developer to know about user status and if they are offline would
be perform some proper message.
You can use many approaches to achieve this task, but I will show the best of
HTML5.
In the HTML5 there is an event that prompts you the internet status.
This is the simplest approach,
navigator.onLine
This is very simple to get the status of the internet. It returns a Boolean value,
true for online and false for offline.
Note The drawback is not supported in all browsers and different
Browsers implement this property differently. However, it is not a full-proof
solution and may not accurate in all conditions.
You can also use another way to to check if the user has the internet connection
or not, by register the events on window.onOnline and window.onOffline
Example:
- <!doctype html><html><head><script>
- function CheckOnlineStatus(msg) {
- var status = document.getElementById("status");
- var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
- var state = document.getElementById("state");
- state.innerHTML = condition;
- }
- function Pageloaded() {
- CheckOnlineStatus("load");
- document.body.addEventListener("offline", function () {
- CheckOnlineStatus("offline")
- }, false);
- document.body.addEventListener("online", function () {
- CheckOnlineStatus("online")
- }, false);
- }
- </script><style>
- ...</style></head><body onload="Pageloaded()"><div id="status"><p id="state"></p></div></body></html>