如何用 JavaScript 檢測瀏覽器是否線上或離線?
要使用 JavaScript 檢測瀏覽器是處於線上還是離線狀態,可以使用以下程式碼:
示例
<!DOCTYPE html> <html> <body> <h1>Online or offline with JavaScript example</h1> <h2>Click the button below to check if you are online or not</h2> <button onclick="checkOnlineOffline()">Check online/offline</button> <h2 class="sample"></p> <script> function checkOnlineOffline() { if(navigator.onLine===true){ document.querySelector('.sample').innerHTML = "You are connected to internet" } else { document.querySelector('.sample').innerHTML = "You are not connected to internet" } } </script> </body> </html>
輸出
上述程式碼將生成以下輸出:
點選“檢查線上/離線”按鈕:
廣告