2017-03-01 48 views
0

我想要一個簡單的代碼,用於檢查瀏覽器內部的互聯網連接以及處理各種代碼的處理,這些代碼將會返回。如何通過javascript在瀏覽器中查看在線/離線狀態?

我已經嘗試了一個http-get-request來處理返回的狀態碼,但最後我對同源策略有一些問題。

我也嘗試了ononline和onoffline事件,但這些都是depricated,並不能在我的目標瀏覽器中工作。

我的第三個選擇是navigator.onLine。當瀏覽器獲得Internet連接時,輸出爲true。但是,當我的瀏覽器沒有連接時,navigator.online的答案不是錯誤的...

我的主要用例是檢查瀏覽器是否連接到互聯網。如果他有Internet連接,那麼他應該打開www.abc.de 但是如果沒有互聯網連接,他應該用localhost:8080/abc打開一個本地應用程序。

回答

3

原則上這是Why navigator.onLine is inconsistent? Is there any reliable solutions?

重複不過,我會親自嘗試像

if (location.host.indexOf("localhost")==-1) { // we are not already on localhost 
    var img = new Image(); 
    img.onerror=function() { location.replace("http://localhost:8080/abc"); } 
    img.src="http://servertotest.com/favicon.ico?rnd="+new Date().getTime(); 
} 
+0

中被解僱了,這是件好事。感謝您的信息 –

+0

這對我很好。當沒有互聯網連接時,需要加載離線頁面。但是:我怎麼能實現,在成功加載其他頁面加載? onload是錯誤的選項,在每次刷新時都會導致錯誤 –

+0

如果服務器啓動,您希望加載「http://servertotest.com/abc」?你可以使用'img.onload = function(){if(location.host.indexOf(「servertotest」)== - 1)location.replace(「http://servertotest.com/abc」)}'這將重定向從本地主機或文件系統到服務器上的網址 – mplungjan

相關問題