Hook for injecting HTML in previewer

I want to modify the preview of a card by injecting some HTML code in it with a hook, just after the question or the answer are rendered.

I found hooks to do this in the reviewer (reviewer_did_show_question and reviewer_did_answer_card, used reviewer.web.eval(script) to inject my code) but I can’t find anything similar for the previewer.
Wrapping Previewer.render_card or Browser._renderPreview did not work.
I’m using Anki 2.1.35 by the way.

Which hook should I be using, or which method should I wrap ?
Thank you in advance !

See the webview_will_set_content hook: anki/genhooks_gui.py at f3b8022a4c8dcbbba3d3a8ae4684aa4624c7c56d · ankitects/anki · GitHub

Your hook will look something like this:

def on_webview_will_set_content(web_content, context):
	if not isinstance(context, aqt.previewer.Previewer):
		# not previewer, do nothing
	# do something

Thank you for your answer, abdo !

It works for injecting code once when the previewer opens, but not when changing the card or revealing the answer.

def on_webview_will_set_content(web_content: WebContent, context):
    if isinstance(context, Previewer):
        ts = time.time()
        card = context.card()
        web_content.body += f"<div id='my-addon'>PREVIEWER {ts} {card.nid}</div>"

The ts and card.nid do not change when I switch from one card to the next, or when I reveal the answer.

Sorry I should have specified it before, but my addon displays a graph (computed with Python code) that depends on the card, and it also changes between the question and answer.

Is there a way to do this ?
As a last resort, maybe rewriting the computation in javascript would work ? :confused:

In that case, try the card_will_show hook instead, which is called once for each side of the card. See anki/genhooks_gui.py at 9c1c2984265c6d11364d49d1babf461f188fd39c · ankitects/anki · GitHub

def on_card_will_show(text: str, card: Card, kind: str) -> str:
    if kind.startswith("preview"):
		return text + "add your code"


The kind argument is used to differentiate between different contexts. See Search · card_will_show · GitHub for possible values.


It worked perfectly, thank you so much !