首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插件如何增强Anki的JavaScript?

插件如何增强Anki的JavaScript?
EN

Stack Overflow用户
提问于 2014-04-20 13:40:04
回答 1查看 3.2K关注 0票数 14

Anki允许卡片使用JavaScript。例如,一张卡片可以包含如下内容:

代码语言:javascript
复制
<script>
//JavaScript code here
</script>

当显示卡时,JavaScript代码将被执行。

为了允许这种脚本与Anki后端交互(例如,为了更改便笺字段的值、添加标记、影响调度等等),我想为Anki编写一个插件(版本2),它将实现一些后端函数,并使卡片的JavaScript脚本能够调用它们。

例如,假设我的插件中有一个(Python)函数,它与Anki的对象交互:

代码语言:javascript
复制
def myFunc():
# use plug-in's ability to interact with Anki's objects to do stuff

我希望允许卡片的JavaScript调用该函数,例如,在卡片中有这样的东西:

代码语言:javascript
复制
<script>
myFunc(); // This should invoke the plug-in's myFunc().
</script>

我知道如何添加钩子,以便各种Anki事件调用我的插件函数,但我希望允许卡内的JavaScript这样做。这一切都能做到吗?如果是的话,那怎么做呢?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-26 11:57:40

在阅读了由@Louis链接的帖子,并与一些同事讨论了这个问题,并尝试了各种不同的事情之后,我终于想出了一个解决方案:

这个想法可以概括在以下两个要点(和两个子关键点):

  • 插件可以创建一个或多个对象,这些对象将被“公开”到卡片的JavaScript脚本中,这样卡片脚本就可以访问这些对象--它们的字段和方法--就好像它们是脚本范围的一部分一样。
代码语言:javascript
复制
- in order to do it the objects must be instances of a specific class (or subclass thereof), and each method and property that is to be exposed to card scripts must be declared as such with a proper PyQt decorator.

  • PyQt提供了将这些对象“注入”到the视图的功能。
代码语言:javascript
复制
- The plug-in has to ensure this injection occurs every time Anki's reviewer's webview is (re-)initialised.

下面的代码显示了如何实现这一点。它为卡片脚本提供了一种检查当前状态的方法(“问题”或“答案”),以及访问(读,更重要的是写)便条字段的方法。

代码语言:javascript
复制
from aqt import mw              # Anki's main window object
from aqt import mw QObject      # Our exposed object will be an instance of a subclass of QObject.
from aqt import mw pyqtSlot     # a decorator for exposed methods
from aqt import mw pyqtProperty # a decorator for exposed properties

from anki.hooks import wrap     # We will need this to hook to specific Anki functions in order to make sure the injection happens in time.

# a class whose instance(s) we can expose to card scripts
class CardScriptObject(QObject):
    # some "private" fields - card scripts cannot access these directly 
    _state = None
    _card = None
    _note = None

    # Using pyqtProperty we create a property accessible from the card script.
    # We have to provide the type of the property (in this case str).
    # The second argument is a getter method.
    # This property is read-only. To make it writeable we would add a setter method as a third argument.
    state = pyqtProperty(str, lambda self: self._state)

    # The following methods are exposed to the card script owing to the pyqtSlot decorator.
    # Without it they would be "private".
    @pyqtSlot(str, result = str) # We have to provide the argument type(s) (excluding self),
                                 # as well as the type of the return value - with the named result argument, if a value is to be returned.
    def getField(self, name):
        return self._note[name]

    # Another method, without a return value:
    @pyqtSlot(str, str)
    def setField(self, name, value):
        self._note[name] = value
        self._note.flush()

    # An example of a method that can be invoked with two different signatures -
    # pyqtSlot has to be used for each possible signature:
    # (This method replaces the above two.
    # All three have been included here for the sake of the example.)
    @pyqtSlot(str, result = str)
    @pyqtSlot(str, str)
    def field(self, name, value = None): # sets a field if value given, gets a field otherwise
        if value is None: return self._note[name]
        self._note[name] = value
        self._note.flush()

cardScriptObject = CardScriptObject() # the object to expose to card scripts
flag = None # This flag is used in the injection process, which follows.

# This is a hook to Anki's reviewer's _initWeb method.
# It lets the plug-in know the reviewer's webview is being initialised.
# (It would be too early to perform the injection here, as this method is called before the webview is initialised.
# And it would be too late to do it after _initWeb, as the first card would have already been shown.
# Hence this mechanism.)
def _initWeb():
    global flag
    flag = True

# This is a hook to Anki's reviewer's _showQuestion method.
# It populates our cardScriptObject's "private" fields with the relevant values,
# and more importantly, it exposes ("injects") the object to the webview's JavaScript scope -
# but only if this is the first card since the last initialisation, otherwise the object is already exposed.
def _showQuestion():
    global cardScriptObject, flag
    if flag:
        flag = False
        # The following line does the injection.
        # In this example our cardScriptObject will be accessible from card scripts
        # using the name pluginObject.
        mw.web.page().mainFrame().addToJavaScriptWindowObject("pluginObject", cardScriptObject)
    cardScriptObject._state = "question"
    cardScriptObject._card = mw.reviewer.card
    cardScriptObject._note = mw.reviewer.card.note()

# The following hook to Anki's reviewer's _showAnswer is not necessary for the injection,
# but in this example it serves to update the state.
def _showAnswer():
    global cardScriptObject
    cardScriptObject._state = "answer"

# adding our hooks
# In order to already have our object injected when the first card is shown (so that its scripts can "enjoy" this plug-in),
# and in order for the card scripts to have access to up-to-date information,
# our hooks must be executed _before_ the relevant Anki methods.
mw.reviewer._initWeb = wrap(mw.reviewer._initWeb, _initWeb, "before")
mw.reviewer._showQuestion = wrap(mw.reviewer._showQuestion, _showQuestion, "before")
mw.reviewer._showAnswer = wrap(mw.reviewer._showAnswer, _showAnswer, "before")

就是这个!安装了这样一个插件后,卡内的JavaScript脚本可以使用pluginObject.state检查它是作为问题的一部分运行,还是作为答案的一部分运行(也可以通过使用设置变量的脚本在答案模板中包装问题部分来实现,但这更整洁),pluginObject.field(名称)从备注中获得字段的值(也可以通过使用Anki的预处理器将字段直接注入JavaScript代码)和pluginObject.field(名称、值)来设置注释中字段的值(直到现在才能完成,据我所知)。当然,许多其他功能可以被编程到我们的CardScriptObject中,以允许卡片脚本做更多的事情(读取/更改配置、实现另一种问答机制、与调度程序交互等等)。

如果有人能提出改进的话,我很想听听。具体来说,我感兴趣的是:

  • 有否更清晰的方法公开方法和属性,使签名更具灵活性;及
  • 是否有一种不那么麻烦的方法来执行注入。
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23183105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档