首页 > 解决方案 > 服务器发送的事件无法使用 JavaFX WebView

问题描述

我用 React 和 MobX 开发了一个单页应用程序。为了从后端代码中获取一些进度信息,例如复制文件进度,我在 javascript 代码中使用了 Server Sent Events 和 EventSource。在任何浏览器中,我都可以成功获取事件消息并显示进度。React 从 EventSource onmessage 事件中获取更改并将更改呈现在屏幕上。这是我将 EventSource 添加到我的 js 代码的方法。(对于那些询问事件源的消息格式是否正确的人?是的,它是在浏览器上工作的。)

代码:


    fetchEvents(url) {

        let evtSource = new EventSource(url);

        evtSource.onmessage = (message) => {
            const data = JSON.parse(message.data);
            //assign data to an observable variable
        }
    }

但是,我需要将我的单页应用程序嵌入到 Java 应用程序中。为此,我使用 JavaFX WebEngine 和 WebView 来加载我的 React 应用程序。除了 Server Sent Events 和 EventSource 消息之外,所有功能都运行良好。不调用 onmessage()、onopen()、onerror() 方法。因此,我无法将数据更改显示在屏幕上。在我的 javascript 代码中,我无法通过 EventSource 获取任何信息。这是JavaFX代码;

代码:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        primaryStage.setTitle("localhost");

        WebView myBrowser = new WebView();
        WebEngine myWebEngine = myBrowser.getEngine();
        myWebEngine.setJavaScriptEnabled(true);
        myWebEngine.load("http://localhost:8080");

        StackPane root = new StackPane();
        root.getChildren().addAll(myBrowser, reloadButton);

        primaryStage.setScene(new Scene(root, 800, 640));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

JavaFX WebView 不支持 EventSource 和服务器发送事件吗?我很好奇有没有办法让 SSE 在 JavaFX WebView 中工作?或者是否有任何其他可能的解决方案可以将我的单页应用程序嵌入到 Java 代码中,并且 EventSource 和服务器发送事件运行良好。

谢谢你。

标签: reactjsjavafxserver-sent-eventsjavafx-webengineeventsource

解决方案


推荐阅读