How can I get implement this to addon to get card counts?

I am implementing this feature. Getting cards count (New, Learn, Review) using javascript. I have tried this https://stackoverflow.com/questions/23183105/how-can-a-plug-in-enhance-ankis-javascript

This is my initial code. How can I add pyqtslot and make it accessible in JavaScript like
console.log(getNewCardCount())
or
console.log(AnkiJS.getNewCardCount()) ?

_ init _.py

from aqt import mw

scheduled_counts = list(mw.col.sched.counts())
cards = {}
cards['new'] = scheduled_counts[0]
cards['learning'] = scheduled_counts[1]
cards['review'] = scheduled_counts[2]

def getNewCardCount():
    return cards['new']

def getLrnCardCount():
    return cards['learning']

def getRevCardCount():
    return cards['review']

Maybe the SO post you linked is for Anki 2.0. The following is an example of implementing something similar to the feature you are describing on Anki 2.1.

add-on code:
from typing import Any, Tuple

import aqt
from aqt import gui_hooks, mw


command_prefix = "AnkiJS."


def on_webview_did_receive_js_message(
    handled: Tuple[bool, Any], message: str, context: Any
):
    # Run only on the reviewer's webview
    if not isinstance(context, aqt.reviewer.Reviewer):
        return handled

    if message.startswith(command_prefix):
        ret = None
        try:
            new, lrn, rev = mw.col.sched.counts(mw.reviewer.card)
            cmd = message[len(command_prefix) :].strip()
            ret = None
            if cmd == "getNewCardCount()":
                ret = new
            elif cmd == "getLrnCardCount()":
                ret = lrn
            elif cmd == "getRevCardCount()":
                ret = rev
        except Exception as e:
            ret = repr(e)
        finally:
            return (True, ret)
    else:
        return handled


gui_hooks.webview_did_receive_js_message.append(on_webview_did_receive_js_message)

JavaScript example:

pycmd(`AnkiJS.getNewCardCount()`, (ret) => {
    console.log(ret);
});

Screenshot:

For more information about pycmd, see the following link:

3 Likes

Thank you

Using your solution I have made JavaScript API for Anki.
https://github.com/infinyte7/AnkiJS-API

For AnkiDroid there is a way to register for API. It get “api version” and “developer name”. So, Can you tell me how to pass value from reviewer to my addon to It get processed and check for api is equal to version defined in addon.
In AnkiDroid, It is implemented as.
https://github.com/ankidroid/Anki-Android/wiki/AnkiDroid-Javascript-API#initialize

How can I pass string from reviewer to addon?
Thanks