Search code examples
javaandroidmathjax

MathJax Rendering is not working properly in Android


I want to render some MathJax code by using MathJax-3.2.2 in WebView. So I have written some code for that :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_latex);

    webView = findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new android.webkit.WebViewClient());
    //webView.loadUrl("https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML");

    //initial loading the page
    webView.loadUrl("file:///android_asset/latex_page.html");

    btn = findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String latex = "$$(-b+sqrt(-b^2-4ac)) / (2a)$$";
            String escapedExpression = escapeLatex(latex);
            String javascript = "javascript:MathJax.Hub.Queue(['Typeset', MathJax.Hub, 'output']);" +
                    "document.getElementById('output').innerHTML = '\\(" + escapedExpression + "\\)';";
            webView.loadUrl(javascript);


        }
    });

}

where when Button will press a new MathJax code should be shown by the end but unfortunately the initial rendering is good but when I am trying to update WebView it is showing nothing.

enter image description here

Can anyone help to change the onClick() method so that it will render properly.

latex_page.html is like

<html>

<head>
    <script type="text/javascript" src="file:///android_asset/es5/tex-mml-chtml.js"></script>
    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
            jax: ["input/TeX", "output/CommonHTML"],
            tex2jax: {
                inlineMath: [['$', '$'], ['\\(', '\\)']],
                displayMath: [['$$', '$$'], ['\\[', '\\]']],
                processEscapes: true
            },
            CommonHTML: { linebreaks: { automatic: true } },
            displayAlign: 'center',
            displayIndent: '0'
        });
    </script>
</head>

<body>
    <p> This LaTex cod load during create activity $$ax^2+bx+c=0$$</p>
    <p>New LaTex render should show below:</p>
    <div id="output"></div>
</body>

An Error :

I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'Queue' of undefined", source: file:///android_asset/latex_page.html (1)


Solution

  • You appear to be loading MathJax version 3 (file:///android_asset/es5/tex-mml-chtml.js), but are using version 2 calls (MathJax.Hub). The two versions use very different APIs. See the documentation for help in upgrading to version 3.

    Instead of MathJax.Hub.Queue(['Typeset', MathJax.Hub, 'output']);, try

    MathJax.typesetPromise(['#output']);
    

    instead.