为什么我无法在IntelliJ ToolWindow插件中通过HTML / JS调用Java方法?

时间:2020-05-27 10:27:16

标签: javascript java intellij-idea intellij-plugin

我正在为IntelliJ IDEA创建一个插件,该插件需要将本地静态Web内容(HTML,CSS,JS)加载到ToolWindow中,并从该HTML / JS内容中调用Java方法。我使用JavaFX WebView将HTML内容加载到ToolWindow中。但是,当我尝试从HTML或JS调用Java方法时,该方法不起作用,有时会出现致命错误并导致应用程序崩溃。

请让我知道,还有其他方法可以将静态Web内容集成到ToolWindow中。请在下面找到示例代码。

public class MyToolWindow implements ToolWindowFactory {

private JFXPanel jfxPanel;

@Override
public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
    toolWindow = ToolWindowManager.getInstance(project)
            .getToolWindow(Messages.getMessagePropertyText(Messages.PLUGIN_TITLE));

    JPanel myPanel = new JPanel(new BorderLayout());
    jfxPanel = new JFXPanel();
    createScene();
    myPanel.add(jfxPanel);

    Content findingPanel = toolWindow.getContentManager().getFactory().createContent(myPanel,"",false);
    toolWindow.getContentManager().addContent(findingPanel);
}
public void invokedFromJS() {
    System.out.println("Invoked from JS");
}

private void createScene() {
    Platform.setImplicitExit(false);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            BorderPane borderPane = new BorderPane();
            WebView webComponent = new WebView();
            WebEngine webEngine = webComponent.getEngine();

            webEngine.documentProperty().addListener((obs, oldDoc, newDoc) -> {
                JSObject window = (JSObject) webEngine.executeScript("window");
                window.setMember("app", new TestClass());
            });

            webEngine.load(MyToolWindow.class.getResource("/mypage.html").toString());

            borderPane.setCenter(webComponent);
            Scene scene = new Scene(borderPane,450,600);
            jfxPanel.setScene(scene);

        }
    });
}}

mypage.html

 <html>
 <head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    <script type="text/javascript">
       function m() {
          try {
             window.app.onClick();
          }catch(err) {
             console.log(err);
          }
       }
    </script>
 </head>
 <body>

 <button onclick="m()">Click ME</button>
 </body>
 </html>

0 个答案:

没有答案