Can I call python function in JS or do the reverse?

I wrote an addon to open GoldenDict when I selected a word.

def showAnswer(card):
    # showInfo(card)
    mw.web.eval("""
    function lookup() {
        var txt = "";

        if (window.getSelection) {
            txt = window.getSelection();
        }
        if (txt == "")
            return;
        if (String(txt).length>20)
            return;
        window.location.href = "gdlookup://localhost/" + txt;
        window.getSelection().empty();
    }
    var x = document.getElementsByTagName("body")[0];
    x.onclick = function () {
        lookup();
    }""")

Now I want to also search this word in anki’s browser. Where can I call something like aqt.dialogs.open("Browser", self.mw, search=(SearchNode(...),))?

Anki offers a JS → Python bridge via pycmd (internal name bridgeCommand) that allows sending string messages to the Python side.

See the add-on hook webview_did_receive_js_message for instructions.

You can directly use the return value of JS code with AnkiWebView.evalWithCallback. For example, the DeckBrowser gets the page y offset and uses the return value in its callback:

3 Likes

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