JavaFX WebView load local Javascript file

2019-03-20 04:16发布

I am experimenting with the JavaFX WebView control and I want to use the MathJax Javascript library to render mathematical content.

As a test I have created a basic JavaFX FXML project, added a WebView to the FXML and updated the controller code like so:

public class SampleController implements Initializable {

    @FXML
    private WebView webView;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        webView.getEngine().load(
            "file:///Users/benjamin/Desktop/Page.html");
    }
}

The html file looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script type="text/x-mathjax-config">
            MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
        </script>
        <script type="text/javascript"
                src="/Users/benjamin/Downloads/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
        </script>
    </head>
    <body>
        When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
        $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
    </body>
</html>

This works as expected and produces the following result:

enter image description here

Note that for the test, both the html and JavaScript file paths are hard coded to locations on my hard drive so the next step is to package the html as a resource that is bundled with the application so that it is not looking for local files.

I have updated the controller code to look up the page like this (the html has not been changed).

@Override
public void initialize(URL url, ResourceBundle rb) {
    webView.getEngine().load(
        this.getClass().getResource("Page.html").toExternalForm());
}

but this produces the following result:

enter image description here

As you can see, the mathematical content is no longer rendered.

If I change the html <script> tag to reference the JavaScript from a CDN, then everything works as in the original example but I would like to be able to reference the local JavaScript file (and eventually a version that is bundled with the application).

Is what I'm trying to achieve possible?

1条回答
贼婆χ
2楼-- · 2019-03-20 05:17

Add the MathJax.js file to the same package/folder of Page.html then reference to it as

<script type="text/javascript"
        src="MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
查看更多
登录 后发表回答