WebView.Eval()在自定义渲染器Webview中不起作用

时间:2019-07-05 04:35:52

标签: c# xamarin.forms webview

我已遵循xamarin pcl示例hybridwebview从JavaScript调用C#。

我还想实现一个从C#调用JavaScript的功能。

我试图在hybridwebview示例的顶部使用webview.Eval(script),但是它不会触发Webview中的JavaScript。我也尝试了没有自定义渲染的Webview,它可以正常工作。

对于Webview CustomRenderer,无法使用Eval。.

我的CustomerRender:

public class HybridWebView : WebView
{
  Action<string> action;
  public static readonly BindableProperty UriProperty = BindableProperty.Create (
    propertyName: "Uri",
    returnType: typeof(string),
    declaringType: typeof(HybridWebView),
    defaultValue: default(string));

  public string Uri {
    get { return (string)GetValue (UriProperty); }
    set { SetValue (UriProperty, value); }
  }

  public void RegisterAction (Action<string> callback)
  {
    action = callback;
  }

  public void Cleanup ()
  {
    action = null;
  }

  public void InvokeAction (string data)
  {
    if (action == null || data == null) {
      return;
    }
    action.Invoke (data);
  }
}

在ContentPage中调用评估:

namespace CustomRenderer
{
    public partial class HybridWebViewPage : ContentPage
    {
        public Func<string, Task<string>> EvaluateJavascript { get; set; }

        public HybridWebViewPage ()
        {
            InitializeComponent ();

            hybridWebView.RegisterAction (data => DisplayAlert ("Alert", "Hello " + data, "OK"));
        }

        private void Button_Clicked(object sender, System.EventArgs e)
        {
            var _Script = string.Format("alert('test')");
            hybridWebView.Eval(_Script);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

查看自定义渲染器和这一行

public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>

您使用的渲染器是ViewRenderer而不是WebViewRenderer,此处的HybridWebView并非Web视图,它只是普通视图,因此Eval功能无效。

我想到的解决方法:使用消息传递中心并在自定义渲染器中执行js

表单项目

private void Button_Clicked(object sender, System.EventArgs e)
    {
        var _Script = string.Format("alert('test')");
        MessagingCenter.Send<object,string>(this,"Hi", _Script);
    }

自定义渲染器

      if (Control == null)
        {
            var webView = new Android.Webkit.WebView(_context);
            webView.Settings.JavaScriptEnabled = true;

            webView.SetWebViewClient(new JavascriptWebViewClient($"javascript: {JavascriptFunction}"));

            ////////////////////////add here 
            webView.SetWebChromeClient(new WebChromeClient());
            MessagingCenter.Subscribe<object, string>(this, "Hi", (obj, arg) =>
            {
                webView.EvaluateJavascript(arg, null);
            });
            ///////////////////////

            SetNativeControl(webView);

        }

我的测试

enter image description here