JSexception in webview of java fx?

2019-07-07 06:53发布

问题:

My java Fx webview throws JS exception for following code. Can anyone explain me why?

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 */

回答1:

webengine.load() call is asynchronous. You need to wait until document is loaded before applying javascript. E.g.:

    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));

There is an example from the WebEngine javadoc.