I have implemented a variant on the evaluate JavaScript setup documented here (my purpose being to return a string based on the result of a function): https://webkitgtk.org/reference/webkitgtk/unstable/method.WebView.evaluate_javascript.html
See my variant below, noting that the documentation version only prints, where as my version sets user_data to be a pointer to the result.
web_view_javascript_finish()runs async, so I need to wait for it to finish before I take the value and carry on with the process.I've read about a few methods for waiting (semaphores, mutexes, etc.) but I tried a basic method first, running
while (!result) {}so that when the result goes from NULL to a string value, things will proceed.However, when I run without this line, everything works as expected, and perhaps unsurprisingly, the
printf("result element: %s\n",result);prints null,, I think because it got there before the JavaScript completed.However, with
while (!result) {},web_view_javascript_finished()appears not to run at all (nothing is printed).
I want to resolve this issue before I move forward with any other solution. I welcome your thoughts!
static void
web_view_javascript_finished (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
JSCValue *value;
GError *error = NULL;
value = webkit_web_view_evaluate_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error);
if (!value) {
g_warning ("1 Error running javascript: %s\n", error->message);
g_error_free (error);
return;
}
if (jsc_value_is_string (value)) {
gchar *str_value = jsc_value_to_string (value);
JSCException *exception = jsc_context_get_exception (jsc_value_get_context (value));
if (exception)
g_warning ("2 Error running javascript: %s\n", jsc_exception_get_message (exception));
else
g_print ("3 Script result: %s\n", str_value);
g_free (str_value);
} else {
g_warning ("4 Error running javascript: unexpected return value\n");
}
gchar *str_value = jsc_value_to_string (value);
g_print ("Script result: %s\n", str_value);
user_data = str_value;
g_print ("user_data result: %s\n", user_data
g_object_unref (value);
}
static char *web_view_get_element_info (WebKitWebView *web_view,
const gchar *uuid)
{
gchar *script = g_strdup_printf ("el = window.document.getElementById('%s'); el_rect = el.getBoundingClientRect(); JSON.stringify(el_rect); ");
char *result = NULL;
webkit_web_view_evaluate_javascript (web_view, script, -1, NULL, NULL, NULL, web_view_javascript_finished, &result);
while (!result) {}
printf("result element: %s\n",result);
return web_result;
g_free (script);
}