Here's the beginning of a JavaScriptCore binding (only the necessary
functions to call a Vala callback from JavaScript).

However, it's not perfect. There is some C compiler warning when compiling
'demo.vala'. I have not found a way to suppress it.


Best regards

Frederik
/*
 * 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 ();
}

[CCode (lower_case_cprefix = "JS", cheader_filename = "JavaScriptCore/JavaScript.h")]
namespace JS {
	
	[CCode (cname = "JSObjectCallAsFunctionCallback", has_target = false)]
	public delegate JS.Value? Callback (JS.Context context, JS.Object function, JS.Object this_object, [CCode (array_length_pos = 3.9, array_length_type = "size_t")] JS.Value[] arguments, out JS.Value exception);

	[Compact]
	[CCode (cname = "struct OpaqueJSContext")]
	public class Context {
		[CCode (cname = "JSContextGetGlobalObject")]
		public unowned JS.Object get_global_object ();
		[CCode (cname = "JSObjectMakeFunctionWithCallback")]
		public unowned JS.Object make_function_with_callback (JS.String? name, JS.Callback call_as_function);
		[CCode (cname = "JSObjectSetProperty")]
		public void set_property (JS.Object object, JS.String property_name, JS.Value value, uint attributes = 0, out JS.Value exception = null);
	}

	[Compact]
	[CCode (cname = "struct OpaqueJSValue")]
	public class Value {
	}

	[Compact]
	[CCode (cname = "struct OpaqueJSValue")]
	public class Object : JS.Value {
	}

	[Compact]
	[CCode (cname = "struct OpaqueJSString", free_function = "JSStringRelease")]
	public class String {
		[CCode (cname = "JSStringCreateWithUTF8CString")]
		public String (string utf8_cstring);
	}
}

_______________________________________________
vala-list mailing list
[email protected]
http://mail.gnome.org/mailman/listinfo/vala-list

Reply via email to