Search code examples
javaandroidwebviewmathjax

Use MathJax inside Android Studio WebView?


Ok so I'm trying to use a WebView with a local html file that uses the MathJax library, but when I run it it doesn't use the library. I tired webView.setJavaScriptEnabled() and I made sure it works as an html document on its own not in a WebView.

Here's my code:

package com.example.mathcompetitions;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    WebView webView;

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


        webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webView.loadUrl("file:///android_asset/index.html");

    }


}

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Math Concepts</title>
    <style>
        @font-face{
            font-family:Cambria;
            src:url('file:///android_asset/cambria.ttc')
        }
        body {
            font-family: 'Cambria';
            font-size: 32px;
            font-weight: normal;
            text-align: center;
            background-color: #222;
            color: #eee
        }
    </style>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"> </script>
</head>
<body>
<p id="p">
    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}.\]
</p>
</body>
</html>

Solution

  • Switching to a different API should do the trick. While working on this I was on 29, but switching to 30 fixed it. And as mentioned in the comments <uses-permission android:name="android.permission.INTERNET" /> in the manifest