这是我的解决方案。
已在IE,Opera,Chrome,FireFox,Safari等IE,IOS 8上作为Phonegap WebApp和在Android 4.4.2上作为Phonegap WebApp进行了测试
此解决方案不适用于localhost上的FireFox。
=================================================== ===============================
onlineCheck.js(文件路径:“ root / js / onlineCheck.js”):
var isApp = false;
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
isApp = true;
}
function isOnlineTest() {
alert(checkOnline());
}
function isBrowserOnline(no,yes){
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
if(yes instanceof Function){
yes();
}
}
xhr.onerror = function(){
if(no instanceof Function){
no();
}
}
xhr.open("GET","checkOnline.php",true);
xhr.send();
}
function checkOnline(){
if(isApp)
{
var xhr = new XMLHttpRequest();
var file = "http://dexheimer.cc/apps/kartei/neu/dot.png";
try {
xhr.open('HEAD', file , false);
xhr.send(null);
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e)
{
return false;
}
}else
{
var tmpIsOnline = false;
tmpIsOnline = navigator.onLine;
if(tmpIsOnline || tmpIsOnline == "undefined")
{
try{
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
tmpIsOnline = true;
}
xhr.onerror = function(){
tmpIsOnline = false;
}
xhr.open("GET","checkOnline.php",false);
xhr.send();
}catch (e){
tmpIsOnline = false;
}
}
return tmpIsOnline;
}
}
=================================================== ===============================
index.html(文件路径:“ root / index.html”):
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="js/onlineCheck.js" ></script>
...
</head>
...
<body onload="onLoad()">
...
<div onclick="isOnlineTest()">
Online?
</div>
...
</body>
</html>
=================================================== ===============================
checkOnline.php(文件路径:“ root”):
<?php echo 'true'; ?>