Как обнаружить поддержку тегов MathML (<mfrac>, <mtable>) из JavaScript? - PullRequest
0 голосов
/ 28 января 2011

Я могу обнаружить поддержку MathML с помощью:

var e = document.createElement('div');
    e.innerHTML = '<math></math>';
    var mathMLSupported = e.firstChild && "namespaceURI" in e.firstChild && e.firstChild.namespaceURI == 'http://www.w3.org/1998/Math/MathML';

, но как определить поддержку <mfrac> и <mtable>?

Ответы [ 4 ]

3 голосов
/ 20 марта 2011

В jqmath я создаю скрытый элемент <mfrac> и сравниваю его вычисленную высоту с не дробной. См. Функцию M.checkMathML в jqmath-0.1.js для реального кода. Это немного усложняется попыткой работать с пространствами имен XML или без них (в зависимости от браузера) и с учетом префикса пространства имен для плагина MathPlayer для Internet Explorer.

1 голос
/ 23 августа 2016

С Element#getBoundingClientRect

function hasMathMLSupport() {
  const div = document.createElement("div");
  div.innerHTML = '<math><mspace height="20px" width="20px"></mspace></math>';
  document.body.appendChild(div);
  return div.firstChild.firstChild.getBoundingClientRect().height === 20;
}

console.log(hasMathMLSupport());

С window.getComputedStyle

function hasMathMLSupport() {
  const div = document.createElement("div");
  div.innerHTML = '<math><mrow mathcolor=\"red\"><mn>1</mn></mrow></math>';
  document.body.appendChild(div);
  return window.getComputedStyle(div.firstChild.firstChild, null).color === "rgb(255, 0, 0)";
}

console.log(hasMathMLSupport());

С Element.querySelector(":link"): (Safari 10+, Firefox? +)

function hasMathMLSupport() {
  const div = document.createElement("div");
  div.innerHTML = '<math><mrow href=\"https://ya.ru\"><mn>1</mn></mrow></math>';
  document.body.appendChild(div);
  return !!div.querySelector(":link");
}

console.log(hasMathMLSupport());
1 голос
/ 03 марта 2015

Это все еще не кажется прямым.

http://www.w3.org/TR/MathML2/chapter8.html

Поддержка объектной модели документа MathML может быть запрошена путем вызова метода DOMImplementation :: hasFeature со строкой теста "org.w3c.dom.mathml"

Это подразумевает простой тест, однако Chrome и IE поддерживают его через плагины, но Chrome возвращает true , даже если у него нет плагина

Мое решение состоит в том, чтобы использовать спецификацию w3c, но это подходит для случаев, когда браузер [chrome] имеет противоположный ответ. Тогда я могу использовать MathJax при необходимости, который всегда, кроме Firefox. Скрипт идет в html разделе

<script type="text/javascript">

  //Browser detector for Chrome
  //returns true if the Browser is Chrome
  function isChrome(){
    var regex = /Chrome\/[0-9]{1,2}\.[0-9]/
    var matches = navigator.userAgent.match(regex)
    //console.log( matches )
    return (matches!=null && matches.length==1)
  }

  /*
   *  Feature Detect for MathML as w3c specification
   *  <returns>boolean: true if mathML is supported in browser
   */
  function hasFeatureMathML(){
    MATHML_FEATURE = "org.w3c.dom.mathml"     //as per w3c specification
    MATHML_FEATURE_VERSION = "2.0"            //Any version number appears to work
    if(isChrome()) return false               //Opps Chrome not natively supported yet
    return document.implementation.hasFeature(MATHML_FEATURE, MATHML_FEATURE_VERSION )
  }

  /*
   * init MathML use MathJax according to
   *     http://docs.mathjax.org/en/latest/dynamic.html
   * with additional test to confirm necessity
   * <returns>boolean: true if mathML is supported in browser
   */
  function initMathML(){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";

    //doctorBob added test on next line, return if has native support for MathML
    if( hasFeatureMathML() ) return true

    document.getElementsByTagName("head")[0].appendChild(script)
    return false
  }

  //initialize in html <head> incase MathJax is required
  var browserHasMathML = initMathML()
  if( !browserHasMathML )console.log("No Native MathML using MathJax")

</script>

Я не особо задумывался об установке плагинов для браузера, потому что не у всех они установлены. Это работает в IE 8, Chrome 39, Firefox 38, Komodo Edit 6

1 голос
/ 28 января 2011

После этого документа соответствующие браузеры должны реализовать несколько свойств (привязок a.k.a.) для определенных элементов MathML в DOM. Поэтому вы можете просто создать элемент MathML mtable и проверить, добавляет ли браузер, например, свойство rowalign:

var tmp = document.createElementNS('http://www.w3.org/1998/Math/MathML',
                                   'mtable');
if (tmp.hasOwnProperty('rowalign')) {
  return true;
} else {
  return false;
}
...