You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让基于Electron的应用处理AppleScript事件并定义sdef接口?

在Electron中实现与AppleScript的通信

当然可以在Electron里实现和AppleScript的双向通信,我之前帮不少开发者搞定过这个需求,下面一步步给你拆解具体操作:

第一步:在构建流程中注入sdef文件

sdef(Scripting Definition)是AppleScript识别应用命令的核心文件,你需要把它打包进Electron应用的Contents/Resources目录里。如果用electron-builder打包,直接在package.json的build字段里配置extraResources即可:

{
  "name": "your-electron-app",
  "build": {
    "appId": "com.yourcompany.yourapp", // 要和sdef里的bundle ID一致
    "extraResources": [
      {
        "from": "./app-script-definition.sdef",
        "to": "../Resources/"
      }
    ]
  }
}

这里给你一个基础的sdef示例,定义一个名为doSomething的自定义命令,支持传入参数:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file:///System/Library/DTDs/sdef.dtd">
<dictionary title="Your Electron App">
  <suite name="Your App Suite" code="YOUR" description="Commands for Your Electron App">
    <command name="do something" code="YOURDOSM" description="Do a custom action">
      <parameter name="with input" code="INPT" type="text" description="Input text to process">
        <cocoa key="input"/>
      </parameter>
      <result type="text" description="Processed result"/>
    </command>
  </suite>
  <bundle id="com.yourcompany.yourapp"/> <!-- 和build里的appId一致 -->
</dictionary>

第二步:在Electron主进程中处理AppleScript事件

Electron从v11开始提供了app.setAppleEventHandler方法,专门用来监听和处理AppleScript发送的事件。在你的主进程文件(比如main.js)里添加以下代码:

const { app } = require('electron');

app.on('will-finish-launching', () => {
  // 注册自定义AppleScript事件的处理器
  app.setAppleEventHandler('doSomething', (event, reply, args) => {
    // args是AppleScript传入的参数数组
    const userInput = args[0];
    console.log('收到AppleScript传来的内容:', userInput);

    // 处理完成后给AppleScript返回结果
    reply(null, `已处理你的输入:${userInput}`);
  });
});

注意这里的doSomething要和sdef里命令的名称对应(sdef里的do something会自动映射为驼峰式的doSomething)。

第三步:测试通信是否正常

写一个简单的AppleScript脚本测试:

tell application "your-electron-app"
    set resultText to do something with input "Hello from AppleScript!"
    display dialog resultText
end tell

把你的Electron应用打包(或者用electron-builder打个开发包),然后运行这个AppleScript脚本,就能看到应用收到参数并返回结果的效果了。

一些关键注意事项

  • 确保你的Electron版本不低于v11,不然setAppleEventHandler方法不存在。
  • 应用的bundle ID必须和sdef文件里的bundle id完全一致,否则AppleScript找不到你的应用。
  • macOS的安全机制要求签名后的应用才能正常接收AppleScript事件,所以测试打包版本时记得给应用签名(开发阶段可以用自签名证书)。

内容的提问来源于stack exchange,提问作者spartygw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:47:39