您好,我正在使用Xamarin(Hybrid WebView)中的示例代码
public class Test : WKNavigationDelegate
{
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
}
}
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>, IWKScriptMessageHandler
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
WKUserContentController userController;
protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged (e);
if (Control == null) {
userController = new WKUserContentController ();
var script = new WKUserScript (new NSString (JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript (script);
userController.AddScriptMessageHandler (this, "invokeAction");
var config = new WKWebViewConfiguration { UserContentController = userController };
config.WebsiteDataStore = WKWebsiteDataStore.DefaultDataStore;
var webView = new WKWebView (Frame, config);
webView.NavigationDelegate = new Test();
SetNativeControl (webView);
}
if (e.OldElement != null) {
userController.RemoveAllUserScripts ();
userController.RemoveScriptMessageHandler ("invokeAction");
var hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup ();
}
if (e.NewElement != null) {
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", "index.html"));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
}
}
public void DidReceiveScriptMessage (WKUserContentController userContentController, WKScriptMessage message)
{
Element.InvokeAction (message.Body.ToString ());
}
}
代码可以运行本地存储在应用程序的Content文件夹中的html文件。当我更改为新的NSUrlRequest时(新的NSUrl(“ http://www.google.com”,false)));页面为空白。
答案 0 :(得分:0)
解决方案:
在自定义渲染器中查看这部分代码:
if (e.NewElement != null) {
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", "index.html"));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
}
此处的网址正在组合应用程序中的本地路径。因此,它将成功加载本地HTML,并且当您更改为new NSUrlRequest (new NSUrl ("http://www.google.com", false)))
时将无法使用。
因此,如果要加载网站,则应将代码更改为:
if (e.NewElement != null) {
//string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", Element.Uri));
//Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
//test
//Control.LoadRequest(new NSUrlRequest(new NSUrl("https://preview.pro.ant.design/user/login")));
Control.LoadRequest (new NSUrlRequest (new NSUrl (Element.Uri)));
}