Search code examples
webkitwebkitgtk

How to inject CSS into webkit?


On Linux I'm creating a webkit window which needs to display a certain URL. I'm doing that like the following:

GtkWidget *main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

// Create a browser instance
WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());

// Put the browser area into the main window
gtk_container_add(GTK_CONTAINER(main_window), GTK_WIDGET(webView));

// Load a web page into the browser instance
webkit_web_view_load_uri(webView, "http://example.com");

// Make sure that when the browser area becomes visible, it will get mouse
// and keyboard events
gtk_widget_grab_focus(GTK_WIDGET(webView));

// Show the result
gtk_window_set_default_size(GTK_WINDOW(main_window), 800, 600);
gtk_widget_show_all(main_window);

However, I need to inject some CSS into this to hide a certain checkbox. How do I inject CSS into the DOM.

I see that I can get the dom like

WebKitDOMDocument *dom = webkit_web_view_get_dom_document(webView);

But from here I can't see how to inject the CSS.


Solution

  • Its not clear which Webkit GTK version you are using, however concepts essentially remain same for both versions. For webkit version 2, its slightly more complicated as DOM manipulation is done on extension side.

    You need to reach to the desired element - either by id e.webkit-dom-document-get-element-by-id or by name. This will return you instance of WebElement. If you use by name call, please be ware that there could be multiple elements with same name

    From here you can either set the style by setting appropriate style attribute webkit_dom_element_set_attribute or other variations that can deal with styles and css rules.

    Or you can take easy option and just execute the javascript that does the same thing by calling webkit_web_view_run_javascript