是否可以 return 将 JXBrowser 呈现的 JS 确认对话框的结果返回到调用它的 JS 部分?

Is it possible to return the result of a JS confirmation dialog presented by JXBrowser back to the JS section that called it?

当加载到浏览器的网页调用 Window.alert 或 window.confirm 时,我正在使用 JavaFX/JXBrowser 显示 alert/dialog。但是,我不知道如何将确认对话框 (true/false) 的结果 return 传递给 JS。由于 alert.showAndWait() 是一个阻塞函数,JS 应该等待这个结果。但是,showAndWait 也在 Platform.runLater runnable 中调用,所以我无法 return 结果。除了编写 JS 函数来执行 true/false 代码并根据 showAndWait 的结果调用它们之外,还有其他选择吗?

browser.setDialogHandler(new DialogHandler() {
@Override
        public CloseStatus onConfirmation(DialogParams params) {
            Platform.runLater(new Runnable() {

                @Override
                public void run() {
                    Alert alert = new Alert(AlertType.CONFIRMATION);
                    alert.setTitle("Yes/No");
                    alert.setHeaderText(null);
                    alert.setContentText("Yes/No");
                    Optional<ButtonType> result = alert.showAndWait();
                    if(result.isPresent())
                    {
                        if(result.get()==ButtonType.YES)
                        {
                            //Send true to calling JS function
                        }else
                        {
                            //Send false to calling JS function
                        }

                    }else
                    {
                        System.out.println("No result!");
                    }
                }
            });
            return null; //because I need to return something and I can't figure out how to get values from the runnable
        }
...
}

您可以使用以下方法:

@Override
public CloseStatus onConfirmation(DialogParams params) {
    final AtomicReference<CloseStatus> status = new AtomicReference<CloseStatus>();
    final CountDownLatch latch = new CountDownLatch(1);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle("Yes/No");
            alert.setHeaderText(null);
            alert.setContentText("Yes/No");
            Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent()) {
                if (result.get() == ButtonType.YES) {
                    status.set(CloseStatus.OK);
                } else {
                    status.set(CloseStatus.CANCEL);
                }

            } else {
                System.out.println("No result!");
            }
        }
    });
    try {
        latch.await();
    } catch (InterruptedException ignored) {
        Thread.currentThread().interrupt();
    }
    return status.get();
}