jcef中js与java相互调用,java与js相互调用,chrome与java相互调用,java与chrome相互调用、jcef与java相互调用
前提:https://blog.csdn.net/weixin_44480167/article/details/133170970(java内嵌浏览器CEF-JAVA、jcef、java chrome)
转自:https://lingkang.top/archives/jcef-zhong-js-yu-java-jiao-hu
代码如下
package top.lingkang;import me.friwi.jcefmaven.CefAppBuilder;
import me.friwi.jcefmaven.CefBuildInfo;
import me.friwi.jcefmaven.MavenCefAppHandlerAdapter;
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.browser.CefMessageRouter;
import org.cef.callback.CefQueryCallback;
import org.cef.handler.CefMessageRouterHandlerAdapter;import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;/*** @author lingkang* @created in 2023/9/22**/
public class Demo02 {public static void main(String[] args) throws Exception {CefAppBuilder builder = new CefAppBuilder();// window下不需要OSRboolean useOSR = false;builder.getCefSettings().windowless_rendering_enabled = useOSR;builder.setAppHandler(new MavenCefAppHandlerAdapter() {@Overridepublic void stateHasChanged(org.cef.CefApp.CefAppState state) {// 关闭应用时退出jvm运行if (state == CefApp.CefAppState.TERMINATED) System.exit(0);}});// 设置cef运行参数,这里为空builder.addJcefArgs(args);// 设置 cef chrome实例的目录,关键,若不设置他会默认从网络中下载,国外网络可能下载不稳定导致失败// 我的 cef chrome 位于项目的chrome目录下 C:\Users\Administrator\Desktop\project\java\demo-desktop\chromebuilder.setInstallDir(new File(System.getProperty("user.dir") + File.separator + "chrome"));// 由于是手动设置cef的chrome,我们要跳过ins检查,防止版本不一致导致从镜像站下载builder.setSkipInstallation(true);// 全局的 CefApp 每个程序只能有一个,线程安全CefApp build = builder.build();// 显示一些版本信息CefBuildInfo buildInfo = CefBuildInfo.fromClasspath();System.out.println(buildInfo);CefApp.CefVersion cefVersion = build.getVersion();System.out.println(cefVersion);// 创建一个浏览器客户端实例CefClient client = build.createClient();// 添加一个方法用于html调用它,在html中执行 window.javaQuery({...})CefMessageRouter.CefMessageRouterConfig config = new CefMessageRouter.CefMessageRouterConfig();config.jsQueryFunction = "javaQuery";// 定义方法config.jsCancelFunction = "javaQueryCancel";// 定义取消方法CefMessageRouter messageRouter = CefMessageRouter.create(config);messageRouter.addHandler(new CefMessageRouterHandlerAdapter() {@Overridepublic boolean onQuery(CefBrowser browser, CefFrame frame, long queryId, String request, boolean persistent, CefQueryCallback callback) {if ("my_call".equals(request)){// 返回影响成功的数据callback.success("get java data success!");browser.executeJavaScript("htmlFun('哈哈')",null,2);// 调用js中定义的方法// callback.failure();return true;}return false;}}, false);client.addMessageRouter(messageRouter);boolean isTransparent = true;// 透明背景// src/main/resources/index.htmlString path = Demo02.class.getResource("/index.html").getPath();// 返回的是一个 url 对象路径path=path.substring(1);// 创建一个浏览器实例CefBrowser browser = client.createBrowser(path, useOSR, isTransparent);// 获取UI组件Component uiComponent = browser.getUIComponent();// 创建 JFrame UI 用于放入chromeJFrame main = new JFrame("lingkang");main.getContentPane().add(uiComponent, BorderLayout.CENTER);main.setSize(800, 600);//大小main.setLocation(0, 0);//位置main.setVisible(true);//显示main.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {// 关闭应用时要释放资源CefApp.getInstance().dispose();main.dispose();System.exit(0);//0正常退出,1非正常退出}});}
}
src/main/resources/index.html
如下
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<button onclick="callJava()">调用java的javaQuery方法</button>
<script>// JavaScript调用java中的方法function callJava(){window.javaQuery({request: 'my_call',persistent: false,onSuccess: function(response) { alert(response) },onFailure: function(error_code, error_message) {}})}// java调用JavaScript中的方法function htmlFun(v){console.log(v)}
</script>
</body>
</html>
效果