javascript-automation - 在 JXA (AppleScript JS) 中加载脚本库

标签 javascript-automation

我创建了一个包含一些库函数的自定义 .scpt 文件,并希望在我的其他脚本中加载该库。

我关注了the official guide由 Apple 提供,这是我得到的:

A) 使用 AppleScript 进行测试

库文件:~/Library/Script Libraries/Sample Library 1.scpt

on changeCase(theText)
    set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
    set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    set theAlteredText to ""
    
    repeat with aCharacter in theText
        set theOffset to offset of aCharacter in theComparisonCharacters
        if theOffset is not 0 then
            set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
        else
            set theAlteredText to (theAlteredText & aCharacter) as string
        end if
    end repeat
    return theAlteredText
end changeCase

测试脚本

tell script "Sample Library 1"
    changeCase("Hello World")
end tell

结果:此解决方案有效。但我想使用 JXA,所以我创建了下面的第二个测试用例。

B) 使用 JXA 进行测试

库文件:~/Library/Script Libraries/Sample Library 2.scpt

function changeCase(text) {
    return text.toUpperCase();
}

测试脚本

var lib = Library("Sample Library 2")
lib.changeCase("Hello World")

👉 结果:当我运行脚本时,脚本编辑器崩溃。错误报告中显示以下错误

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSXMLDocument initWithData:options:error:]: nil argument'
abort() called
terminating with uncaught exception of type NSException

这里发生了什么,如何修复使用 JXA 时的崩溃?

最佳答案

我找到了解决方案:

库文件~/Library/Script Libraries/Sample Library 2.scpt需要是一个扩展名为.scptd的“脚本包”

摘要:

  1. JXA 库需要保存为“Script-Bundles”(“另存为... → Script-Bundle”)。
  2. JXA 库只能由其他 JXA 脚本使用
  3. AppleScript 文件永远无法加载 JXA 库。
  4. “Script”类型的 AppleScript 库可供其他 AppleScript 文件使用。
  5. JXA 脚本和 AppleScript 文件可以使用属于“Script-Bundles”的 AppleScript 库。

为了简单起见,我建议将所有库保存为“脚本包”

关于javascript-automation - 在 JXA (AppleScript JS) 中加载脚本库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69887840/

相关文章:

javascript - JXA 和 OmniGraffle

javascript - jxa - 在 JavaScript 中获取 NSAttributedString 字体指标以实现自动化

javascript - 优胜美地(OS X 10.10)上是否有javascript GUI自动化的引用

javascript - 如何从 cocoa 应用程序运行 JavaScript/AppleScript?

javascript - Javascript for Automation (JXA) 中的比较/丰富查询 "whose()"

javascript - 使用 `runScript`函数运行JXA脚本不允许参数

javascript - 删除 JXA(用于自动化的 Javascript)中的元素和/或元素-容器关系

JavaScript macOS 错误 : Named parameters must be passed as an object

linux - 在 Unix/macOS 系统事件上触发脚本

javascript-automation - 使用 JXA 发送系统事件按键向下/向上