4

我的 java Fx webview 为以下代码引发 JS 异常。谁能解释我为什么?

WebView webview = new WebView();
WebEngine webengine=webview.getEngine();
newtab.setText("Start Page");
newtab.setContent(webview);
editTabset.getTabs().add(newtab);
webengine.load("file:///E:/myproj/src/novuseditor/resources/html/clike.html");/*works till here*/
webengine.executeScript("document.getElementById('code').value=\"Hi\"");
/*exception:netscape.javascript.JSException: TypeError: 'null' is not an object */
4

1 回答 1

11

webengine.load()调用是异步的。在应用 javascript 之前,您需要等到文档加载完毕。例如:

    WebView webview = new WebView();
    final WebEngine webengine = webview.getEngine();
    webengine.getLoadWorker().stateProperty().addListener(
    new ChangeListener<State>() {
        public void changed(ObservableValue ov, State oldState, State newState) {
            if (newState == Worker.State.SUCCEEDED) {
                webengine.executeScript("document.getElementById('header').innerHTML = '<p>Hi</p>';");
            }
        }
    });
    webengine.load("http://stackoverflow.com");
    primaryStage.setScene(new Scene(webview, 400, 400));

WebEngine javadoc 中有一个示例。

于 2012-04-05T07:22:59.697 回答