Skip to content

External MathML files with object does not work with MathJax

Clément Pit-Claudel edited this page Jul 10, 2020 · 6 revisions

From https://groups.google.com/d/msg/mathjax-users/5VOt3rJXHms/X1_ovYTCm5MJ

See also https://github.com/mathjax/MathJax/issues/2456 for an updated (MathJax v3) version.


Is there a way that I can embed external MathML files in a HTML document? Usually I would do it with <object>. Sadly this seems not to work with MathJax. Is there another way?


Well, I did some experiments and it looks like the files don't need to contain anything other than a <math> tag. I don't know how you are setting the height and width, however (my tests indicate that the browsers simply use a default width and height that has nothing to do with the actual contents of the file). Also the baseline would need to be adjusted if you were using in-line math, and it is not clear how to determine that either.

In any case, assuming that your xml files contain a single <math> tag, I have the following suggestion. Add

<script type="text/x-mathjax-config">
MathJax.Extension.object2jax = {
  version: "1.0",
  PreProcess: function (element) {
    if (typeof(element) === "string") {element = document.getElementById(element)}
    if (!element) {element = document.body}
    var objects = element.getElementsByTagName("object");
    for (var i = objects.length-1; i >= 0; i--) {
      var object = objects[i];
      var math = ((object.contentDocument||{}).documentElement||{});
      if (String(math.nodeName).toLowerCase() === "math") {
        math = document.importNode(math,true);
        object.parentNode.insertBefore(math,object);
        object.parentNode.removeChild(object);
      }
    }
  }
};
MathJax.Hub.Register.PreProcessor(["PreProcess",MathJax.Extension.object2jax],5);
          // priority 5 is before mml2jax
</script>

somewhere before the script that loads MathJax.js (or put it in your local configuration file if you are using one). This will register a preprocessor that will look for <math> elements in <object> tags and will incorporate them into the body of the document, where the mml2jax preprocesor will be able to recognize and handle them. Note that this avoids having to specify a height and width for the <object>, since the <object> is actually removed and the MathML is inserted into the document directly. This also gets the baseline to work properly, too, when you are using in-line math.

Anyway, I think that will do what you need.

Davide

Clone this wiki locally