How to get the right-clicked audio filename in webview context menu event?

I’ve been shown how I can catch the right-click event inside of the reviewer:

def _reviewerContextMenu(webview: AnkiWebView, menu: QMenu):
    if mw.state != "review":
        return
    page: QWebEnginePage = webview.page()
    ...

gui_hooks.webview_will_show_context_menu.append(_reviewerContextMenu)

Now I want to get the value of the onclick="pycmd('play:q:0')" attribute of the right-clicked audio element (if the user did right-click an audio element)

However I can’t find any methods in AnkiWebView, QWebEngineView, QWebEnginePage, QMenu, or any children of them, that allow me to get the HTML element that was right-clicked. Hopefully I have simply missed something.

How can I get the value of the onclick="pycmd('play:q:0')" attribute of the audio tag that was right-clicked?

Try the following:

import aqt

js = """
function getSoundLinkOnclickAttr() {
    const replayButton = [...document.querySelectorAll(".replay-button")].find((ele) =>
        ele.contains(document.activeElement)
    );
    return replayButton ? replayButton.getAttribute("onclick").split(";")[0] : "";
}
getSoundLinkOnclickAttr();
"""


def on_webview_will_show_context_menu(
    webview: aqt.webview.AnkiWebView, menu: aqt.qt.QMenu
) -> None:
    def callback(onclick_attr: str) -> None:
        if onclick_attr:
            menu.addAction(onclick_attr, lambda *_: print("hello"))

    if aqt.mw.state == "review" and webview.title == "main webview":
        webview.evalWithCallback(js, callback)


aqt.gui_hooks.webview_will_show_context_menu.append(on_webview_will_show_context_menu)

forum#14638

4 Likes