简单代码:
((WebKit.DOM.EventTarget) img).add_event_listener_with_closure ("click", on_enter, false);
void on_enter() {
}
valac错误:
error: Argument 2: Cannot convert from `on_enter' to `GLib.Closure'
以下是完整的代码示例:
private void on_click(WebKit.DOM.EventTarget target, WebKit.DOM.Event event)
{
try
{
//var image = (WebKit.DOM.HTMLImageElement)target;
//image.set_attribute("class", "clickable-img-hover");
}
catch(GLib.Error e)
{
}
}
public static void webkit_web_extension_initialize (WebKit.WebExtension web_extension)
{
string PROG = "[webkit2_webextension_minimal_so.so] ";
print(PROG + "PLUGIN activated\n");
web_extension.page_created.connect((extension, web_page)=> {
print(PROG + "SIGNAL: page_created\n");
try {
var dom = web_page.get_dom_document();
WebKit.DOM.Element img = dom.create_element("img");
img.set_attribute("src", "file:///home/o/avatar.png");
img.set_attribute("alt", "avatar-1.jpg");
((WebKit.DOM.EventTarget) img).add_event_listener_with_closure("click", on_click, false);
dom.body.insert_before(img, null);
} catch (FileError e) {
stdout.printf ("Message: \"%s\"\n", e.message);
stdout.printf ("Error code: FileError.EXIST = %d\n", e.code);
stdout.printf ("FileErrors identification: %" + uint32.FORMAT + "\n", e.domain);
}
web_page.send_request.connect((request)=> {
if(request.uri.has_prefix("http://www.google") || request.uri.has_prefix("data")){
print(PROG + "SIGNAL: send request [REJECTED] " + request.uri + "\n");
return true; // true => block query
}
print(PROG + "SIGNAL: send request " + request.uri + "\n");
return false;
});
return;
});
}
编译:
valac --pkg glib-2.0 --pkg webkit2gtk-web-extension-4.0 --library=webext webext.vala -H webext.h -X -fPIC -X -shared -o webext.so
如何添加事件监听器?
PS:这是对this earlier question的跟进问题。
答案 0 :(得分:1)
查看documentation for the method:
public bool add_event_listener_with_closure (
string event_name,
owned EventTargetFunc handler,
bool use_capture
)
第二个参数是owned EventTargetFunc handler
。
所以看看documentation of the delegate type:
public delegate void EventTargetFunc (EventTarget target, Event event)
您的方法没有此delgate类型。
因此,您可能必须将方法签名修改为:
void on_enter (EventTarget target, Event event) {
}