Inserting HTML at cursor via `insertHTML` behaves differently depending on system

Hi! I’ve made this add-on (GitHub - xkevio/typst-anki) mostly for me as a utility to utilize Typst math syntax instead of LaTeX (MathJax) and it works reasonably well. It either invokes the typst compiler and outputs an SVG string which I insert on the card, or invokes pandoc to convert it to MathJax for more native support inside of Anki.

It is supposed to insert the output right at the cursor, as appending it would break inside HTML elements like lists. I use the deprecated document.execCommand('insertHTML', ...) (see typst-anki/src/typst_anki/__init__.py at main · xkevio/typst-anki · GitHub) for this and it works perfect on my Windows 11 machine but not on my Arch Linux machine. There it seems to prepend the output at the beginning of the note, regardless of cursor position. Any ideas as to why and how to fix that?

I have tried invoking even more custom JavaScript via getSelection(), node.appendChild() or insertAdjacentHTML and so on – this only inserts content visually but doesn’t store it on the card.

Each Qt version has an associated Chromium version, and the Chromium version you’re using on Arch is likely older or newer than the one Anki ships with.

Yeah, I figured it might be a mismatch between the underlying web engines. However, I still find it hard to believe that that would break insertHTML entirely like that. I will check the corresponding Chromium versions on my Linux system and try to match them.

In the meantime, is there a more idiomatic way to insert at the cursor since document.execCommand is deprecated?

it seems to prepend the output at the beginning of the note, regardless of cursor position

I think I’ve run into a similar problem. Sometimes with my addons the text got inserted at the beginning of a field instead of the cursor position. I don’t remember at the moment if it depended on the OS used.

I’m also interested in a proper solution. I’ve added the following code as a workaround last year:

Maybe something similar is useful here?

Thank you, this workaround almost works! It inserts the text at the cursor position again, however it inserts the MathJax as pure text first, so \(x = 3\) for example and it only transforms into pure math when opening the HTML field or triggering some other kind of editor update.

I managed to fix it before with editor.saveNow(editor.loadNoteKeepingFocus) and that still works when I don’t use setTimeout so it’s a bit confusing. I made sure to use evalWithCallback just in case it was a timing issue but it persists.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.