一、加载/显示WebView
// 创建 JBCefBrowser
JBCefBrowser jbCefBrowser = new JBCefBrowser();
// 将 JBCefBrowser 的UI控件设置到Panel中
this.content.add(jbCefBrowser.getComponent(), BorderLayout.CENTER);
// 加载URL
jbCefBrowser.loadURL(YOUR_URL);
js 向 java通信
<script type="text/javascript">
function callJava(arg) {
;
}
</script>
- 通过 JBCefJSQuery 拦截、接收js侧callJava方法,参考代码:
JBCefJSQuery query = JBCefJSQuery.create((JBCefBrowserBase) browser);
query.addHandler((String arg) -> {
try {
JSONObject requestAsJson = JSON.parseObject(arg);
System.out.println("in Handler fast json" + requestAsJson.toJSONString());
return new JBCefJSQuery.Response("msg");
} catch (Exception e) {
return new JBCefJSQuery.Response(null, 0, "errorMsg");
}
});
browser.getJBCefClient().addLoadHandler(new CefLoadHandler() {
@Override
public void onLoadingStateChange(CefBrowser cefBrowser, boolean isLoading, boolean canGoBack, boolean canGoForward) {
}
@Override
public void onLoadStart(CefBrowser cefBrowser, CefFrame frame, CefRequest.TransitionType transitionType) {
}
@Override
public void onLoadEnd(CefBrowser cefBrowser, CefFrame frame, int httpStatusCode) {
System.out.println("onLoadEnd");
cefBrowser.executeJavaScript(
"window.callJava = function(arg) {" +
query.inject(
"arg",
"response => console.log('callJava 成功', response)",
"(error_code, error_message) => console.log('callJava 失败', error_code, error_message)"
) +
"};",
null, 0);
}
@Override
public void onLoadError(CefBrowser cefBrowser, CefFrame frame, ErrorCode errorCode, String errorText, String failedUrl) {
}
}, browser.getCefBrowser());
}