簡體   English   中英

如何在加載網頁之前檢查Chrome中的初始Internet連接

[英]How to Check for an Initial Internet Connection in Chrome before loading a Web Page

我正在建立一個網絡信息亭。 電腦啟動並直接進入Chrome。 瀏覽器在建立網絡連接之前加載,因此用戶始終看到的第一件事是連接錯誤。

我正在嘗試創建一個等待連接啟動的初始本地托管網頁,然后將頁面重定向到網絡上托管的實時網頁。

我試過了:

navigator.onLine

但在Chrome中,這僅檢查瀏覽器是否處於“在線模式”,而不是實際上是否存在有效連接。 結果是它總是重定向到沒有連接的實時頁面,並且用戶得到連接錯誤。

我嘗試過AJAX請求,但結果總是如此:

Access-Control-Allow-Origin不允許使用origin http://localhost

我無法使用任何標志啟動Chrome以禁用此功能。 它必須是Chrome的默認風格。

所以我的問題是:這個問題有解決方案嗎? 我願意使用Javascript / JQuery / PHP / HTML等任意組合。

這是我本地托管網頁的代碼:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Kiosk Splash</title>
  <link rel=stylesheet type="text/css" href="jquery/css/ui-lightness/jquery-ui-1.10.2.custom.css">
  <script src="jquery/js/jquery-1.9.1.js"></script>
  <script src="jquery/js/jquery-ui-1.10.2.custom.js"></script>
</head>
<body>
<div id="dialog" style="text-align:center;">
    <p>
        <font font face="verdana" size="5">The Kiosk is establishing a connection to the network...</font>
    </p>
    <div id="progressbar" style="width: 50%; margin: 0 auto;"></div>
</div>
<script>
$( "#dialog" ).dialog({ minWidth: 1000 });
$(".ui-dialog-titlebar-close", this.parentNode).hide();
$( "#progressbar" ).width(800);
$( "#progressbar" ).progressbar({
  value: false
});
      function connect(){
      try{
        $.ajax({url:"http://intranet/webpage",
        statusCode: {
    200: function() {
      window.location.replace("http://live/webpage");
    }
  },
     error: function(e){
         console.log(e);
         setTimeout(connect, 5000);
     }, 
       dataType:"json"
   });
}catch(e){
     console.log(e);         
    setTimeout(connect, 5000);
}
} 
connect();
</script>
</body>
</html>

一個非常骯臟的黑客與JSONP和jquery

使用jsfiddle jsonp測試:

(function testConnection() {
  setTimeout(testConnection, 2000);
  $.getJSON("http://jsfiddle.net/echo/jsonp/?callback=redirect&cb=?");
})()

function redirect() {
   window.location = 'http://www.google.com'; // REDIRECT TARGET
}

第一版:

(function testConnection() {
    setTimeout(testConnection, 2000);
    $.getJSON(
       "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
       {format:'json'}
    ).done(function(result){
        window.location = 'http://www.google.com'; // REDIRECT TARGET
    });
})()

按預期工作,您可能希望擁有自己的Web服務器,以便不依賴於特定的API

此行為旨在防止從localhost連接的惡意腳本,當然,當您嘗試實現自助服務終端時,這只是一種痛苦。

我認為你需要做的是與這個相當不同的問題中的答案相同: Access-Control-Allow-Origin不允許使用Origin

Matt Mombrea建議這樣的事情:

Access-Control-Allow-Origin: *

“這將允許跨域AJAX。在PHP中你需要像這樣修改響應:”

<?php header('Access-Control-Allow-Origin: *'); ?>

然后,您可以輪詢您控制的在線服務器,使用此訪問控制權限進行響應,以查看您的互聯網連接是否已啟用。

否則,您可以使用localhost PHP服務器腳本嘗試訪問服務器,並讓您的ajax localhost頁面查詢localhost腳本以獲取答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM