evaluateJavascript

open fun evaluateJavascript(script: String, length: Long, worldName: String? = null, sourceUri: String? = null, cancellable: <Error class: unknown class>? = null, callback: <Error class: unknown class>?)

Asynchronously evaluate @script in the script world with name @world_name of the main frame current context in @web_view. If @world_name is null, the default world is used. Any value that is not null is a distinct world. The @source_uri will be shown in exceptions and doesn't affect the behavior of the script. When not provided, the document URL is used.

Note that if #WebKitSettings:enable-javascript is false, this method will do nothing. If you want to use this method but still prevent web content from executing its own JavaScript, then use #WebKitSettings:enable-javascript-markup.

When the operation is finished, @callback will be called. You can then call webkit_web_view_evaluate_javascript_finish() to get the result of the operation.

This is an example of using webkit_web_view_evaluate_javascript() with a script returning a string:

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 ("Error running javascript: %s", 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 ("Error running javascript: %s", jsc_exception_get_message (exception));
else
g_print ("Script result: %s\n", str_value);
g_free (str_value);
} else {
g_warning ("Error running javascript: unexpected return value");
}
g_object_unref (value);
}

static void
web_view_get_link_url (WebKitWebView *web_view,
const gchar *link_id)
{
gchar *script = g_strdup_printf ("window.document.getElementById('%s').href;", link_id);
webkit_web_view_evaluate_javascript (web_view, script, -1, NULL, NULL, NULL, web_view_javascript_finished, NULL);
g_free (script);
}

Since

2.40

Parameters

script

the script to evaluate

length

length of @script, or -1 if @script is a nul-terminated string

worldName

the name of a #WebKitScriptWorld or null to use the default

sourceUri

the source URI

cancellable

a #GCancellable or null to ignore

callback

a #GAsyncReadyCallback to call when the script finished