2018-09-13

使用 javascript 在 automator 執行簡單的按鍵精靈

現在 automator 已經可以用 javascript 寫,不用再 applescript 惹。

用法

進階

為了方便 Terminal,或是 GUI 直接執行

檔案內容第一行可加上 shebang 指定執行環境

#!/usr/bin/env osascript -l JavaScript

function run (input, parameters) { ... }

並賦予執行權限 chmod +x ./run.js

之後 Terminal 下就可以直接 ./run.js 惹。

GUI 想要直接執行的話,記得右鍵 Open With 選 Terminal.app 執行。

例子

wow 簡易自動使用技能

function run(input, parameters) {
  let sys = Application('System Events')

  // debug 用
  // let currentApp = Application.currentApplication()
  // currentApp.includeStandardAdditions = true

  delay(3) // 3 秒後再正式開始執行

  while (true) {
    // 查詢有在前景的所有 process
    let procList = sys.processes.whose({
      frontmost: true,
    })

    // 找到前景裡面第一個,也就是當前 focus 的 app
    let firstProc = procList.length ? procList.at(0) : undefined
    let props = firstProc ? firstProc.properties() : {}

    // 在 macos 裡的 alert 用法
    // currentApp.displayAlert(JSON.stringify(props))

    // 判斷一下是否是該 app,不然一直全局執行很煩
    if (props.name === 'World of Warcraft') {
      delay(Math.floor(Math.random()) + 1)
      // tab 是 wow 切換目標的熱鍵
      sys.keystroke('	')
      delay(Math.floor(Math.random()) + 0.5)
      // 我個人設定熱鍵 shift+3 (#) 冰霜震擊
      sys.keystroke('#')
    }
  }

  return input
}

References