我正在尝试在我的项目中处理 webview 超时。
如果我想在启动时检查网络连接,我可以这样做:
if(!CrossConnectivity.Current.IsConnected)
{
//You are offline, notify the user
return null;
}
但问题是,我想检查确切的网站是否有连接。
这应该在网站内导航期间发生。(可能有些页面超时,我应该
向他人显示消息)这是我的代码:
string url = "xxxxxxxxx.xxxxxx";
webview.Source = url;
Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("Custom", (handler, view) =>
{
#if ANDROID
handler.PlatformView.Settings.CacheMode = Android.Webkit.CacheModes.Default;
handler.PlatformView.Settings.SetAppCacheEnabled(true);
handler.PlatformView.Settings.JavaScriptEnabled = true;
handler.PlatformView.AddJavascriptInterface(new JavaScriptHandler(), "Native");
#endif
});
我尝试过 Maui IsConnected 方法,但它没有解决我的问题。
WebView 有 Navigation 和 Navigated 事件
您可以尝试使用 Webview 的 Navigated 事件。
<WebView x:Name="mywebview" Navigated="mywebview_Navigated" .../>
在代码隐藏事件处理程序中,您可以根据如下结果实现逻辑(例如显示警报):
void mywebview_Navigated(System.Object sender, Microsoft.Maui.Controls.WebNavigatedEventArgs e)
{
switch (e.Result)
{
case WebNavigationResult.Cancel:
// your logic
break;
case WebNavigationResult.Failure:
// your logic
break;
case WebNavigationResult.Success:
// your logic
break;
case WebNavigationResult.Timeout:
// your logic
break;
default:
// your logic
break;
}
}
希望有帮助!