Anki Forums

[regression?] javascript issue with let and const variable assignation

Hi,

I know javascript is not officialy supported and don’t want to waste your time but I ran into an issue and apparently fixed it so I wanted to report to you.

Basically I switched from 2.1.35 to 2.1.44 (ubuntu 18) and my template stopped working. It uses javascript quite a lot but the issue was weird : the was only executed during the first review. All the reviews after that one would silently ignore the code. If I went back to the deck screen then resumed reviewing the script would execute but again only during the first review.

Weirder : if, in the middle of reviewing cards of my template I had a review of another template (image occlusion in that case) then the review after that one would execute the js code correctly.

Wild : the ignored script was only the front section and not the back section. Meaning that pressing the spacebar would flip the card and then execute the back section.

Wilder : every problem went away when I turned all the “const variable_name” and “let variable_name” to “var variable_name”

So that was the workaround I used but I don’t yet know if that will cause issues down the line.

I checked the changelog to see if I saw anything relevant between 2.1.35 and 2.1.44 and didn’t find a thing so I figured it might be a regression.

Of course I tried with addons turned off and the problem remained unchanged.

Have a nice day!

edit : the issue doesn’t seem to come from a variable having the same name in the front and back section, as confirmed by putting “let test = “test”” at the top of my script, it stopped working after the first review instantly

I guess this is because Anki uses a single webview for the review session and just changes parts of it for each card (recycling the webview periodically). You have to manually execute your code for each card, maybe relying on hooks to trigger it, depending on what your code is trying to do.

2 Likes

Hi,
thanks a lot for the quick response.

As it’s only a template and not an addon, would you be so kind as to give me a few directions on how to “manually execute my code for each card”?

My code is quite messy but can be found here : Clozolkor/latest_release at main · thiswillbeyourgithub/Clozolkor · GitHub

The explanation is in the README here : GitHub - thiswillbeyourgithub/Clozolkor: enhancing "cloze one by one" script by iTraveller

Thanks a lot!

I think you can append a script element that calls on your code to the question/answer text using the card_will_show hook. See anki/genhooks_gui.py at 968bd1b27aae04d7f61dac33515c70fca9fbfc78 · ankitects/anki · GitHub

Best practice would be to move your code into an IIFE.

1 Like

Thanks a lot!

I tried using IIFE after your suggestion but it seems to break thing in ankidroid. So I’ll just keep my code as it is.

Thanks a lot again!