if(navigator.onLine) { // true|false // ... }
window.addEventListener('online', function(e){console.log('online')});
window.addEventListener('offline', function(e){console.log('offline');});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用 JavaScript 檢測(cè)瀏覽器在線/離線狀態(tài)(JavaScript API?—?navigator.onLine)</title>
<style type="text/css"> #status {
position: fixed;
width: 100%;
font: bold 1em sans-serif;
color: #FFF;
padding: 0.5em;
}
#log {
padding: 2.5em 0.5em 0.5em;
font: 1em sans-serif;
}
.online {
background: green;
}
.offline {
background: red;
} </style>
</head>
<body>
<div id="status"></div>
<div id="log"></div>
<button type="button" id="test">檢查狀態(tài)</button>
<script> window.addEventListener('load', function () { var testBtn = document.getElementById("test"); var status = document.getElementById("status"); var log = document.getElementById("log");
function updateOnlineStatus(event) { var condition = navigator.onLine ? "online" : "offline";
status.className = condition;
status.innerHTML = condition.toUpperCase();
log.insertAdjacentHTML("beforeend", "Event: " + (event?event.type:"-") + "; Status: " + condition+ " | ");
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
testBtn.addEventListener("click", updateOnlineStatus);
updateOnlineStatus();
}); </script>
</body>
</html>