Java 内嵌Chromium浏览器

Java 内嵌Chromium浏览器 JCEF

测试后在Swing中正常运行,JavaFX尚未成功运行

运行效果

在这里插入图片描述

背景

有个项目想要渲染html网页,使用JavaFX的WebView后发现有些js库无法正常运行,想到之前了解过的JCEF项目
在之前只能自己编译打包JCEF,很麻烦
突然发现了JCEFMaven项目

JCEF Github地址
JCEFMvaen项目 Github地址

Maven添加依赖

<dependency>
    <groupId>me.friwi</groupId>
    <artifactId>jcefmaven</artifactId>
    <version>116.0.19</version>
</dependency>

项目测试代码

public class MainFrame extends JFrame {
    private static final long serialVersionUID = -5570653778104813836L; 
    private final JTextField address_;
    private final CefApp cefApp_;
    private final CefClient client_;
    private final CefBrowser browser_;
    private final Component browerUI_;
    private boolean browserFocus_ = true;

    /**
     * To display a simple browser window, it suffices completely to create an
     * instance of the class CefBrowser and to assign its UI component to your
     * application (e.g. to your content pane).
     * But to be more verbose, this CTOR keeps an instance of each object on the
     * way to the browser UI.
     */
    MainFrame(String startURL, boolean useOSR, boolean isTransparent, String[] args) throws UnsupportedPlatformException, CefInitializationException, IOException, InterruptedException {
        CefAppBuilder builder = new CefAppBuilder();
        builder.getCefSettings().windowless_rendering_enabled = useOSR;
        builder.setAppHandler(new MavenCefAppHandlerAdapter() {
            @Override
            public void stateHasChanged(org.cef.CefApp.CefAppState state) {
                // Shutdown the app if the native CEF part is terminated
                if (state == CefAppState.TERMINATED) System.exit(0);
            }
        });
        if (args.length > 0) {
            builder.addJcefArgs(args);
        }
        cefApp_ = builder.build();
        client_ = cefApp_.createClient();
        // (3) Create a simple message router to receive messages from CEF.
        CefMessageRouter msgRouter = CefMessageRouter.create();
        client_.addMessageRouter(msgRouter);
        browser_ = client_.createBrowser(startURL, useOSR, isTransparent);

        browerUI_ = browser_.getUIComponent();
        address_ = new JTextField(startURL, 100);
        address_.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser_.loadURL(address_.getText());
            }
        });

        // Update the address field when the browser URL changes.
        client_.addDisplayHandler(new CefDisplayHandlerAdapter() {
            @Override
            public void onAddressChange(CefBrowser browser, CefFrame frame, String url) {
                address_.setText(url);
            }
        });

        // Clear focus from the browser when the address field gains focus.
        address_.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (!browserFocus_) return;
                browserFocus_ = false;
                KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
                address_.requestFocus();
            }
        });
        client_.addFocusHandler(new CefFocusHandlerAdapter() {
            @Override
            public void onGotFocus(CefBrowser browser) {
                if (browserFocus_) return;
                browserFocus_ = true;
                KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
                browser.setFocus(true);
            }

            @Override
            public void onTakeFocus(CefBrowser browser, boolean next) {
                browserFocus_ = false;
            }
        });
        getContentPane().add(address_, BorderLayout.NORTH);
        getContentPane().add(browerUI_, BorderLayout.CENTER);
        pack();
        setTitle("JCEF 内嵌chromium");

        setSize(1400, 800);
        setLocationRelativeTo(null);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                CefApp.getInstance().dispose();
                dispose();
            }
        });
    }

    public static void main(String[] args) throws UnsupportedPlatformException, CefInitializationException, IOException, InterruptedException {
        TestReportGenerator.print(args);
        boolean useOsr = false;
        new MainFrame("http://www.baidu.com", useOsr, false, args);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 PySide2 中内嵌 Chromium 浏览器需要使用 QtWebEngineWidgets 模块,而使用 Selenium 控制浏览器则需要安装相应的浏览器驱动。以下是一个简单的示例代码: ```python from PySide2.QtCore import QUrl from PySide2.QtGui import QWindow from PySide2.QtWidgets import QApplication from PySide2.QtWebEngineWidgets import QWebEngineView from selenium import webdriver from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.chrome.options import Options import sys import time class CustomWebEngineView(QWebEngineView): def __init__(self): super().__init__() # 创建一个 Chrome 的 Options 对象 options = Options() options.add_argument('--disable-gpu') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument('--headless') # 创建一个 Chrome 的 WebDriver 对象 self.driver: WebDriver = webdriver.Chrome(options=options) # 加载页面 self.load(QUrl('https://www.baidu.com')) def closeEvent(self, event): # 关闭 WebDriver self.driver.quit() super().closeEvent(event) if __name__ == '__main__': app = QApplication(sys.argv) # 创建一个窗口 window = QWindow() # 创建一个内嵌的 WebEngineView web_view = CustomWebEngineView() web_view.setParent(window) # 显示窗口 window.show() # 进入事件循环 sys.exit(app.exec_()) ``` 在上面的示例代码中,首先我们自定义了一个 `CustomWebEngineView` 类,继承自 `QWebEngineView`,在该类的构造函数中创建了一个 Chrome 的 WebDriver 对象,并加载了一个百度首页的页面。 然后我们创建了一个窗口,并将 `CustomWebEngineView` 对象设置为该窗口的子控件。最后调用 `app.exec_()` 进入事件循环,显示窗口。在窗口关闭时,我们需要手动调用 `driver.quit()` 关闭 WebDriver。 需要注意的是,在使用 PySide2 内嵌 Chromium 浏览器时,由于 Chromium 的多进程架构,我们需要在启动 Chrome 的时候禁用 GPU 和沙盒模式。另外,为了避免浏览器窗口弹出,我们使用了 `--headless` 参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值