How to get selected text in editor window?

This is sample code from addon guides.
I want to get the selected text from any fields for further use in variable.
selectedText = aqt.utils.getText
But didn’t work.

from aqt.utils import showInfo
from anki.hooks import addHook

# cross out the currently selected text
def onStrike(editor):
    editor.web.eval("wrap('<del>', '</del>');")

def addMyButton(buttons, editor):
    editor._links['strike'] = onStrike
    return buttons + [editor._addButton(
        "iconname", # "/full/path/to/icon.png",
        "strike", # link name

addHook("setupEditorButtons", addMyButton)

You can do it with either:

  • QWebEngineView.selectedText()
  • [JavaScript] getSelection().toString()

Here is a simple example:

import aqt
from aqt import gui_hooks

def on_editor_will_show_context_menu(
    editor_webview: aqt.editor.EditorWebView, menu: aqt.QMenu
    # QWebEngineView.selectedText()
    if selected_text := editor_webview.selectedText():
        menu.addAction(f"QWebEngineView.selectedText(): {selected_text}")

    # JavaScript getSelection().toString()
    def callback(text):
        if text:
            menu.addAction(f"getSelection().toString(): {text}")

    editor_webview.evalWithCallback("window.getSelection().toString()", callback)





I am trying to use the gui_hooks.editor_will_show_context_menu hook but it doesn’t seem to fire while the legacy EditorWebView.contextMenuEvent does fire, is there an issue in Anki .48 with regards to this hook? I note that in the same script I am able to get the gui_hooks.editor_will_load_note.append successfully.

I have just tested the above code on 2.1.48 and it works. I guess one of the add-ons you have enabled may be overriding contextMenuEvent instead of using the hook, so that the hook does not fire.

Thanks, I had a look around and you are correct, Image Occlusion Enhanced overrides contextMenuEvent and calls runHook but that obviously won’t trigger the new hooks.