Xamarin Android WebView 访问 sessionStorage returns null

Xamarin Android WebView access to sessionStorage returns null

我有这个自定义 WebViewClient,每次页面完成加载时,我想检查 sessionStorage 的值,使用 javascript 注入来读取存储。

问题是 callbackobj 值始终为 (null)。我做错了什么?

public class CustomWebViewClient : WebViewClient
{

    public override void OnPageFinished(WebView view, string url)
    {
        string script = "window.sessionStorage.getItem('someKey');";
        var callbackobj = InjectJS(view, script);

        base.OnPageFinished(view, url);
    }

    private JsValue InjectJS(WebView view, string script)
    {
        var valueCallback = new JsValue();
        view.EvaluateJavascript(script, valueCallback);

        return valueCallback;

    }
    public class JsValue : Java.Lang.Object, IValueCallback
    {
        public string Value { get; set; }
        public void OnReceiveValue(Java.Lang.Object value)
        {
            this.Value = value.ToString() ?? throw new ArgumentNullException(nameof(value));
        }
    }
}

我还有一个从 here 实现的自定义渲染器,我在其中附加了新的 CustomWebClient。

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

        if (Control == null)
        {
            var webView = new Android.Webkit.WebView(_context);
            webView.SetWebViewClient(new CustomWebViewClient());

            webView.Settings.JavaScriptEnabled = true;
            webView.Settings.DomStorageEnabled = 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(Element.Uri);

        }
    }

编辑:它甚至不能使用简单的脚本作为返回 document.body,不仅是存储访问。问题一定比较笼统。

我已经玩过了,我明白了。

我在使用 EvaluateJavaScript 时不需要 jsBridge。

当脚本更改为

string script = "javascript:(function() { return sessionStorage.getItem('someKey'); })()

有效。

另外我将转换更改为:

public void OnReceiveValue(Java.Lang.Object value)
{
 this.Value = ((Java.Lang.String)value).ToString() ?? throw new ArgumentNullException(nameof(value));
}

EDIT :如果还需要等待 JS 执行,我在这种情况下需要这个答案完成工作 https://forums.xamarin.com/discussion/comment/283373/#Comment_283373