I am trying to embed an HTML view in my Gtk3 program. In that HTML view, I want to use Ajax. Does this work? How could this be achieved.
I made a few experiments in C with the following code:
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>
static void activate(GtkApplication *app, gpointer user_data){
GtkWidget *window = gtk_application_window_new (app);
WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
WebKitSettings *settings = webkit_web_view_get_settings (webView);
webkit_settings_set_enable_javascript (settings, TRUE);
webkit_settings_set_allow_file_access_from_file_urls(settings, TRUE);
webkit_web_view_load_uri(webView, "file:/home/userxy/ajax_gtk_test/test_ajax.html");
gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET(webView));
gtk_widget_show_all (window);
}
int main (int argc, char **argv){
GtkApplication *app;
app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
g_application_run (G_APPLICATION (app), argc, argv);
}
I am compiling the code with gcc `pkg-config --cflags gtk+-3.0` -o example example.c `pkg-config --libs gtk+-3.0` `pkg-config webkit2gtk-4.0 --cflags --libs`
.
The HTML page I am loading is
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<p>This is an AJAX test.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
xhttp.open("GET", "file:/home/userxy/ajax_gtk_test/ajax_info.txt");
xhttp.send();
}
</script>
</body>
</html>
The page is loaded. But it is not updated, after clicking the button.
In a web browser, I can open that file, and the Ajax mechanism works as expected.
The same with "in-place" java script works as expected:
<!DOCTYPE html>
<html>
<body>
<p id="demo">This is an AJAX test.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Ajax works."'>Change Content</button>
</body>
</html>
So it seams that only the reloading mechanism for external files is disabled in Gtk Webkit2. But I don't find a way to enable this.