如何在未连接互联网的情况下在浏览器上自定义消息
本文关键字:情况下 浏览器 自定义消息 互联网 连接 | 更新日期: 2023-09-27 18:21:49
当我的web应用程序无法连接到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);
}
我还没有调试此代码。