INNER CODE UNIT · TypeScript

extractLatexFromKatexNode

RyanYipeng/SyncCaster · apps/extension/src/content-scripts/index.ts:214

function extractLatexFromKatexNode(node: Element, _serializer: XMLSerializer): string {
  const mathml = node.querySelector('.katex-mathml');
  if (!mathml) return '';
  
  // 核心方法:使用 XMLSerializer 序列化原始 MathML,保留 annotation 标签
  // 这是最可靠的方法,因为 innerHTML/outerHTML 可能会丢失 MathML 命名空间内容
  try {
    const serializer = new XMLSerializer();
    const serialized = serializer.serializeToString(mathml);
    console.log('[math] Serialized MathML length:', serialized.length);
    
    // 从序列化的 XML 中提取 annotation
    const annotationMatch = serialized.match(/<(?:m:)?annotation[^>]*encoding=["']application\/x-tex["'][^>]*>([\s\S]*?)<\/(?:m:)?annotation>/i);
    if (annotationMatch && annotationMatch[1]) {
      const tex = decodeHtmlEntities(annotationMatch[1].trim());
      if (tex && tex.length > 0) {
        console.log('[math] Found LaTeX via XMLSerializer:', tex.substring(0, 80));
        return tex;

View source record →

📰 Research Paper
Loading…
⏳ Fetching content…