hookenz
hookenz

Reputation: 38907

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.

Upvotes: 2

Views: 1062

Answers (2)

Michael C.
Michael C.

Reputation: 318

It sounds like the webkit_web_view_run_javascript() answer was a good solution to your specific problem, since you only needed to hide one checkbox.

To answer the general problem of how to inject arbitrary CSS: if you're using a recent version of WebKitGTK+, create a WebKitUserContentManager, call webkit_user_content_manager_add_stylesheet(), and then pass the WebKitUserContentManager when creating your WebKitWebView, either using webkit_web_view_new_with_user_content_manager() or by using g_object_new() manually if you need to set multiple construct-only properties.

Unrelated warning: webkit_web_view_get_dom_document() was removed in WebKitGTK+ 2.6. (The DOM API is only accessible via web process extensions nowadays.) You are using an old, insecure version of WebKitGTK+!

Upvotes: 3

user871199
user871199

Reputation: 1500

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

Upvotes: 1

Related Questions