Issue
I have this custom WebViewClient where every time a Page finish loading I want to check the sessionStorage for a value using javascript injection to read the storage.
The problem is that callbackobj Value is always (null). What am I doing wrong ?
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));
}
}
}
I have also a custom renderer implemented from here where I attach the new 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);
}
}
EDIT: It doesn't even work with simple script as returning document.body, not only storage accessing. The problem must be more general.
Solution
I've played with it and I figured it out.
I don't need jsBridge when using EvaluateJavaScript.
When the script is changed to
string script = "javascript:(function() { return sessionStorage.getItem('someKey'); })()
it works.
Also I changed conversion to be:
public void OnReceiveValue(Java.Lang.Object value)
{
this.Value = ((Java.Lang.String)value).ToString() ?? throw new ArgumentNullException(nameof(value));
}
EDIT : If there is also a need for awaiting the JS to execute which I needed in this scenario this answer did the work https://forums.xamarin.com/discussion/comment/283373/#Comment_283373
Answered By - gneric
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.