DEV Community

Nguyen Quang Trinh
Nguyen Quang Trinh

Posted on

Tích hợp mathjax vào tinymce

Áp dụng cách dùng tinymce cdn (thời điểm sử dụng là v8)

  1. Nhúng tinycme vào trang
  2. Cấu hình tinymce:
<textarea></textarea>
<script type="text/javascript">
    tinymce.init({
        selector: 'textarea',
        plugins: 'table lists',
        toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist | mathjax',
        external_plugins: {'mathjax': '/tinymce-mathjax-master/plugin.min.js'},
        mathjax: {
        lib: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js', //required path to mathjax
        //symbols: {start: '\\(', end: '\\)'}, //optional: mathjax symbols
        //className: "math-tex", //optional: mathjax element class
        //configUrl: '/your-path-to-plugin/@dimakorotkov/tinymce-mathjax/config.js' //optional: mathjax config js
        }
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Nguồn plugin tinymce-mathjax
https://www.npmjs.com/package/@dimakorotkov/tinymce-mathjax
Bổ sung dùng 1 thẻ div để preview công thức, không cần nhúng mathjax vào tinymce:
<div id="question-preview" class="border p-2 mt-2 rounded bg-light"></div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        tinymce.init({
            selector: '#content',
            plugins: 'table lists',
            toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist',
            height: 300,
            setup: function (editor) {
                editor.on('input', function () {
                    updateQuestionPreview(editor);
                });

                // Render preview lần đầu nếu có dữ liệu
                editor.on('init', function () {
                    updateQuestionPreview(editor);
                });
            }
        });

        function updateQuestionPreview(editor) {
            const content = editor.getContent();
            const previewEl = document.getElementById('question-preview');
            previewEl.innerHTML = content;

            if (window.MathJax) {
                MathJax.typesetPromise([previewEl]);
            }
        }
    });
</script>
Enter fullscreen mode Exit fullscreen mode
<script>
    window.MathJax = {
        tex: {
            inlineMath: [['\\(', '\\)']],
            displayMath: [['\\[', '\\]']]
        },
        svg: {
            fontCache: 'global'
        }
    };
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)