WebKit2GTK+ "window-object-cleared" not clearing

394 views Asked by At

This is a follow up to: How to debug WebKit2GTK+ extensions

Here is my extension:

#include <webkit2/webkit-web-extension.h>
#include <iostream>

static void window_object_cleared_callback(WebKitScriptWorld* world, WebKitWebPage* webPage, WebKitFrame* frame, gpointer userData)
{
  std::cout << "Callback reached\n";

  JSCContext *jsCtx = webkit_frame_get_js_context_for_script_world(frame, world);
  JSCValue* title = jsc_context_evaluate(jsCtx, "document.title;", -1);

  std::cout << "Title: " << jsc_value_to_string(title) << "\n";
}

static void web_page_created_callback(WebKitWebExtension* extension, WebKitWebPage* webPage, gpointer UserData)
{
  g_print("Page %lu created for %s\n", webkit_web_page_get_id(webPage), webkit_web_page_get_uri(webPage));
}

extern "C" G_MODULE_EXPORT void webkit_web_extension_initialize(WebKitWebExtension* extension)
{
  g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), NULL);
  g_signal_connect(webkit_script_world_get_default(), "window-object-cleared", G_CALLBACK(window_object_cleared_callback), NULL);
}

The only thing that is printing to the console is "Page 1 created for (null)". This callback for page created is getting called when nothing has been created, is it the same for winow-object-cleared?

I have no idea why the window_object_cleared object is showing now signs of working.

These is what I found on the signal: https://webkitgtk.org/reference/webkit2gtk/stable/WebKitScriptWorld.html#WebKitScriptWorld-window-object-cleared

2

There are 2 answers

0
A student On BEST ANSWER
#include <webkit2/webkit-web-extension.h>
#include <iostream>

static void js_handler(WebKitWebPage* webPage)
{
  JSCContext *jsCtx = webkit_frame_get_js_context(webkit_web_page_get_main_frame(webPage));
  JSCValue* title = jsc_context_evaluate(jsCtx, "document.title;", -1);

  std::cout << "Title: " << jsc_value_to_string(title) << "\n";
}

static void document_loaded_callback(WebKitWebPage* webPage, gpointer userData)
{
  g_print("Page %lu created for %s\n", webkit_web_page_get_id(webPage), webkit_web_page_get_uri(webPage));
  js_handler(webPage);
}

static void web_page_created_callback(WebKitWebExtension* extension, WebKitWebPage* webPage, gpointer userData)
{
  g_signal_connect(webPage, "document-loaded", G_CALLBACK(document_loaded_callback), NULL);
}

extern "C" G_MODULE_EXPORT void webkit_web_extension_initialize(WebKitWebExtension* extension)
{
  g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), NULL);
}

I guess the solution was using the webkit frame to get the JSCContext, and using a signal for "document-loaded" instead of doing "window-object-cleared"

1
lb90 On

The window-object-cleared callback is meant as a way to inject javascript. I think it is only executed when you add at least "some content" to the WebKitWebView. You should call load_uri or the similar functions.