单击按钮不会做什么 - 但为什么。
点击按钮应打印" [Javascript Logger] Aha"。
这里是代码:
public class FormNotCalled extends Form {
public FormNotCalled() {
setTitle("FormNotCalled");
setLayout(new BorderLayout());
setScrollable(false);
BrowserComponent browserComponent = new BrowserComponent();
browserComponent.setPage(
"<html lang=\"en\\\">\n" +
" <body >\n" +
" <button onclick=\"logger.log('Aha');\">Click me</button>\n" +
" </body>\n" +
"</html>",
null);
getContentPane().add(BorderLayout.CENTER, browserComponent);
JavascriptContext javascriptContext = new JavascriptContext(browserComponent);
JSObject logger = (JSObject)javascriptContext.get("{}");
logger.set("log", new JSFunction() {
public void apply(JSObject self, Object[] args) {
String msg = (String)args[0];
Log.p("[Javascript Logger] " + msg);
}
});
javascriptContext.set("window.logger", logger);
}
}
答案 0 :(得分:1)
setPage()是异步的。您需要等到页面加载后才能在其上注册函数。最简单的方法是在onLoad事件中。
e.g。
browserComponent.addWebEventListener(e->{
JSObject logger = (JSObject)javascriptContext.get("{}");
logger.set("log", new JSFunction() {
public void apply(JSObject self, Object[] args) {
String msg = (String)args[0];
Log.p("[Javascript Logger] " + msg);
}
});
javascriptContext.set("window.logger", logger);
});