Xamarin Android HybridWebView,如何动态更改url

时间:2017-03-30 11:12:31

标签: webview xamarin.android hybrid dynamic-url

这是渲染脚本

using Android.Webkit;
using CustomRenderer;
using CustomRenderer.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer (typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace CustomRenderer.Droid
{
    public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>
    {
        const string JavaScriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";

        const string JavaScriptFunction1 = "function invokeCSharpAction1(data){jsBridge.invokeAction1(data);}";

        protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
        {
            base.OnElementChanged (e);

            if (Control == null) {
                var webView = new Android.Webkit.WebView (Forms.Context);
                webView.Settings.JavaScriptEnabled = true;
                SetNativeControl (webView);
            }
            if (e.OldElement != null) {
                Control.RemoveJavascriptInterface ("jsBridge");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup ();
            }
            if (e.NewElement != null) {
                Control.AddJavascriptInterface (new JSBridge (this), "jsBridge");
                Control.LoadUrl ("http://192.168.2.105:64518/login/index");

                InjectJS (JavaScriptFunction);
                InjectJS(JavaScriptFunction1);
            }
        }

        void InjectJS (string script)
        {
            if (Control != null) {
                Control.LoadUrl (string.Format ("javascript: {0}", script));
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您必须覆盖OnElementPropertyChanged并应用您的逻辑来更改其中的网址。例如,跟随渲染器片段对Element中的Source属性更改做出反应:

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        var element = sender as HybridWebView;
        if (e.PropertyName.Equals(HybridWebView.SourceProperty.PropertyName) && element != null)
        {
            Control?.StopLoading();
            var source = element.Source as UrlWebViewSource;
            Control?.Load((source?.Url ?? "").EndsWith("about:blank") ? "about:blank" : source?.Url, null);
        }
    }