[英]How to custom message on browser when internet is not connected
我的Web應用程序無法連接到Internet時,我想顯示自定義消息。
當前,當我的Internet連接失敗時,瀏覽器將顯示"unable to connect" or "server not found"
。 所以我想在頁面上顯示我的自定義消息。
我寫了這個:
bool bb = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (bb == true)
{
//custom message
}
else
//meesage
但是仍然無法正常工作。
我該怎么證明?
我認為您希望瀏覽器可以連接互聯網,如果可以的話,請使用navigator.onLine;。
<script type="text/javascript">
var isOnline = navigator.onLine;
if (!isOnline)
alert("Your custom message for no internet connectivity!!!");
</script>
定期從客戶端到服務器的呼叫,並且如果沒有答案或沒有期望的答案-顯示錯誤消息。
對於Web表單 :創建具有ProcessRequest
實現的處理程序,如下所示:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Ok");
}
對於mvc :創建具有簡單結果的操作,如下所示:
public ActionResult CheckInternetConnection()
{
return Json("Ok");
}
當然,此請求處理程序不應要求任何授權或其他預處理
然后創建js timer
和請求方法
var maxTime = <your interval time>;
var timer;
//write own method for check request
function performRequest() {
var xhr = new XMLHttpRequest();
// reserve 1 sec for timeout function execution
// if we didn't - you can get a situation when
// simultaneously performing more than 1 request
xhr.timeout = maxTime - 1000;
xhr.ontimeout = function {
//waiting to long
alert('<your message>');
window.clearInterval(timer);
};
xhr.open('GET', '<url of your check connection handler>', true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState != 4)
return;
if (xhr.responseText !== 'OK') {
//Can't access to handler
alert('<your message>');
window.clearInterval(timer);
}
}
}
//after page load start request timer
document.onload += function () {
timer = window.setInterval(performRequest, maxTime);
}
我沒有調試此代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.