gpt4 book ai didi

javascript - 插件如何增强 Anki 的 JavaScript?

转载 作者:太空狗 更新时间:2023-10-29 17:48:33 31 4
gpt4 key购买 nike

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

<script>
//JavaScript code here
</script>

JavaScript 代码将在卡片显示时执行。

为了通过使此类脚本与 Anki 后端交互来提供更大的灵 active (例如,为了更改笔记字段的值、添加标签、影响日程安排等),我想为 Anki(版本 2)编写一个插件,实现一些后端功能并启用卡片的 JavaScript 脚本来调用它们。

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

def myFunc():
# use plug-in's ability to interact with Anki's objects to do stuff

我希望能够允许卡片的 JavaScript 调用该函数,例如在卡片中包含这样的内容:

<script>
myFunc(); // This should invoke the plug-in's myFunc().
</script>

我知道如何添加 Hook ,以便各种 Anki 事件调用我的插件功能,但我想允许卡片中的 JavaScript 这样做。这完全可以做到吗?如果可以,那么怎么做?谢谢!

最佳答案

已阅读 post通过@Louis 链接,并与一些同事讨论了这个问题,并尝试了各种方法,我终于想出了一个解决方案:

思想可以概括为这两个关键点(和两个子关键点):

  • 该插件可以创建一个或多个对象,这些对象将“公开”给卡片的 JavaScript 脚本,以便卡片脚本可以访问这些对象 - 它们的字段和方法 - 就好像它们是脚本的范围。

    • 为了做到这一点,对象必须是特定类(或其子类)的实例,并且要向卡片脚本公开的每个方法和属性都必须使用适当的 PyQt 装饰器声明。

  • PyQt 提供了将此类对象“注入(inject)”到 WebView 的功能。

    • 插件必须确保每次(重新)初始化 Anki 的审阅者的 webview 时都会发生这种注入(inject)。

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

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(name) 从注释中获取字段的值(也可以通过使用 Anki 的预处理器将字段直接注入(inject) JavaScript 代码来实现)和 pluginObject.field(name, value) 来设置注释中字段的值(据我所知,到目前为止还不能完成)。当然,可以将许多其他功能编写到我们的 CardScriptObject 中,以允许卡片脚本执行更多操作(读取/更改配置、实现另一个问答机制、与调度程序交互等...)。

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

  • 是否有一种更简洁的方式来公开方法和属性,从而允许更多的签名灵 active ;和
  • 是否有更简单的注入(inject)方法。

关于javascript - 插件如何增强 Anki 的 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23183105/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com