/* * Compile with * $ valac demo.vala --pkg webkit-1.0 --pkg jscore --vapidir . */ using Gtk; using WebKit; namespace WebKit { /* Not bound in webkit-1.0.vapi */ public extern static unowned JS.Context web_frame_get_global_context (WebFrame frame); } /** * Registers a JavaScript function to a WebView */ void register_js_function (WebView webview, string name, JS.Callback callback) { var frame = webview.get_main_frame (); unowned JS.Context ctx = web_frame_get_global_context (frame); unowned JS.Object global = ctx.get_global_object (); unowned JS.Object func = ctx.make_function_with_callback (null, callback); ctx.set_property (global, new JS.String (name), func); } JS.Value? say_hello_callback () { stdout.printf ("hello, world\n"); return null; } JS.Value? say_goodbye_callback () { stdout.printf ("bye\n"); return null; } void main (string[] args) { Gtk.init (ref args); var window = new Window (); window.destroy.connect (Gtk.main_quit); var webview = new WebView (); register_js_function (webview, "sayHello", say_hello_callback); register_js_function (webview, "sayGoodbye", say_goodbye_callback); webview.open ("file://./demo.html"); window.add (webview); window.show_all (); Gtk.main (); }