[Tip] getting the active webview for performing card-related operations

A common pattern I recently find myself repeating in many add-ons that inject scripts to modify card display is a function to get the appropriate webview to execute scripts on using .eval(). Many hooks provide a “context” argument that can be checked to get the webview, but I wanted a method that can be used anywhere, and I came up with this function recently:

from aqt.qt import QApplication
from aqt.webview import AnkiWebView
from aqt.browser.previewer import Previewer
from aqt.clayout import CardLayout

def get_active_webview() -> AnkiWebView:
    dialog = QApplication.activeModalWidget()
    if isinstance(dialog, CardLayout):
        return dialog.preview_web
    window = QApplication.activeWindow()
    if isinstance(window, Previewer):
        return window._web  # pylint: disable=protected-access
    return mw.reviewer.web

If someone notices flaws in this method, or has a better approach, please let me know!