2
votes

I have js function getState() that returns a css property(block or none) of an element but it isn't working, visual studio gives some Thread messages:

09-14 23:30:22.081 W/WebView ( 6707): java.lang.Throwable: A WebView method was called on thread 'Thread-12'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 2) {4aca651} called on null, FYI main Looper is Looper (main, tid 2) {4aca651}) 09-14 23:30:22.081 W/WebView ( 6707): at android.webkit.WebView.checkThread(WebView.java:2539) 09-14 23:30:22.081 W/WebView ( 6707): at android.webkit.WebView.evaluateJavascript(WebView.java:1054) Thread finished: #4

Can any one figure out where is the error? Also, when this be working, the returned type can be associated to a label text or it wouldn't be a simple string?

My code:

        public static Label label1;
        public static WebView webnav;
        StackLayout parent = null;
        public MainPage()
        {
            InitializeComponent();
            webnav = new WebView
            {
                HeightRequest = 1000,
                WidthRequest = 1000,
                Source = "https://www.example.com/test.html",

            };
            webnav.Navigated += WebView_Navigated;

            label1 = new Label
            {
                WidthRequest = 900,
                HeightRequest = 60,
                Text = "default text"
            };

            parent = new StackLayout();
            parent.Children.Add(webnav);
            parent.Children.Add(label1);
            Content = parent;
        }

        public void WebView_Navigated(object sender, WebNavigatedEventArgs e)
        {
            Task.Run(JSRun);
        }

        public static string retorno;
        public static async Task JSRun()
        {
            retorno = await webnav.EvaluateJavaScriptAsync("getState();");
        }
1
it tells you exactly what is wrong "All WebView methods must be called on the same thread"Jason

1 Answers

3
votes

All WebView methods must be called on the same thread... FYI main Looper is Looper (main, tid 2)

You are using a Task.Run to execute a method that in turn calls EvaluateJavaScriptAsync and thus you are not on the Main/UI thread. That is what the error is trying to tell you.

So remove the Task.Run:

public void WebView_Navigated(object sender, WebNavigatedEventArgs e)
{
    JSRun();
}

Or post your EvaluateJavaScriptAsync call to the UI message/looper queue:

Device.BeginInvokeOnMainThread(async() =>
{
    retorno = await webnav.EvaluateJavaScriptAsync("getState();");
});