什么是AppleScript

AppleScript是苹果公司开发的一种脚本语言,用于操作MacOS及其应用程序,在实现MacOS自动化工作方面非常给力。
我们可以使用AppleScript用来完成一些重复琐碎的工作,AppleScript具有简单自然的语法,另外系统也提供了语法查询字典,可以很方便的查询语法
AppleScript前身是HyperTalk

如何使用AppleScript

Mac中带有脚本编辑器可用于调试、运行AppleScript脚本语言

Nodejs调用AppleScript脚本
在Node环境中,AppleScript脚本要被执行,则需要在脚本首行写入shebang: #!/usr/bin/osascript,然后使用child_process模块的exec、execSync等执行AppleScript脚本

child_process.exec('oascript test.scpt')

如何搜索支持AppleScript的应用及其按钮等元素?

  • 通过脚本编辑器的内置字典查看支持AppleSript的应用以及应用的提供的接口
  • 通过第三方工具UI Browser, 选择target可以看到各个软件以及按钮的名字
  • AppleScript 基本语法

    打开Chrome指定标签页

    tell application "Google Chrome"
    	tell front window
    		set theTab to make new tab with properties {URL:"https://www.taobao.com"}
    	end tell
    end tell
    
    set <变量名> to <值>
    
    set baidu to "https://www.baidu.com/"
    set taobao to "http://www.taobao.com"
    set isbaidu to 1
    tell application "Google Chrome"
    	activate
    	if (isbaidu) < 1 then
    		open location huajiao
    		open location baidu
    	end if
    end tell
    
    repeat with num in [1, 2, 3]
    	display dialog num
    end repeat