Can''t get JavaScript to work in WebView

1.7k views Asked by At

I have a fairly simple JavaFX application. It has one window, split in two. On the left is a tableview that lists rows from a database. When you select one of the rows, it displays the XML (also from the database) in a webview on the right. So far so good. I can't for the life of me get any sort of JavaScipt working. My ultimate goal is to get a search and highlight working (as in this great post. Based on my problems there, I thought I'd try and simplify matters by just plugging in a simple JavaScript function to the HTML.

I'm using FXML, if that's relevant. I have a button that for it's OnAction property, calls this method:

    @FXML
    private void searchBrowser() {
        if (webEngine.getDocument() != null) {
            highlight(searchField.getText());           
        } 
    }

    @FXML
    private void highlight(String text) {
        webEngine.executeScript("test()");

It doesn't throw any errors, and both methods are called in order. Just nothing else happens. The test() function is in the HTML, just a simple alert. If I just save the HTML and load it in Chrome or IE, the function works fine. What am I doing wrong?

1

There are 1 answers

3
varren On BEST ANSWER

First of all I can't find easy way to fix old version for webView.getEngine().loadContent();.

But i decided to push the same feature on my project. My requirements where syntactic highlight and selected text highlight, so here is what i came up with: (Code is not really optimised, just works and demonstrates how it can be done)

It is huge code for 1 post ,so i will just explain essential parts and post demo git link. Java git path., Resources git path

  • Google-code-prettify lib for syntactic highlight
  • JQuery + 2 js functions for selected text highlight.
  • Initially I load template HTML file as a string and fix css and js links, because i store them locally and have no idea how to setup relative path in html
  • Then I wrap html encoded XML in template HTML

enter image description here

Old Post works only for webView.getEngine().load():

I don't know what's inside test() js function, but this code looks fine to me. The problem can be when you append your js to the page, because webView.getEngine().load() and webView.getEngine().loadContent(); are both assync tasks, so you have to add listener like this:

webView.getEngine().getLoadWorker().stateProperty().addListener(
            new ChangeListener<Worker.State>() {
                public void changed(ObservableValue ov, 
                                    Worker.State oldState, Worker.State newState) {
                    if (newState == Worker.State.SUCCEEDED) {
                        //some append js code here
                    }
                }
            });

And here is working demo code: https://gist.github.com/varren/1fb41536f2b95f69be4e