简体   繁体   中英

How to custom message on browser when internet is not connected

I want to show custom message when my web application is failed to connect to internet.

Currently when my internet connectivity fails then the browser shows "unable to connect" or "server not found" . so I want to show my custom message on my page.

I have written this :

bool bb = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (bb == true)
{
  //custom message
}
else
   //meesage

But still it is not working.

How can I show that?

I think you are expecting internet connectivity from browser, if so use navigator.onLine;

 <script type="text/javascript">
    var isOnline = navigator.onLine;
    if (!isOnline)
        alert("Your custom message for no internet connectivity!!!");
</script>

Periodically call from client to server, and if there is no answer or not expecting answer - show error message.

for web forms : create handler with implemetation of ProcessRequest like this:

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Ok");
    }

for mvc : create action with simple result like this:

public ActionResult CheckInternetConnection()
{
    return Json("Ok");
}

of course, this request handlers should not require any authorization or another pretreatment

then create js timer and method for request

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);
}

I haven't debug this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM