新建Xcode工程,选择macOS平台,选择Other类型中的AppleScript App。
在工程中找到appleScript后缀文件,在applicationWillFinishLaunching_方法中添加测试代码,此处以Safari为例。
on applicationWillFinishLaunching_(aNotification)
-- Insert code here to initialize your application before any files are opened
--Safari打开网页
tell application "Safari"
activate
--新建tab页,传入URL
tell front window
--get every tab
--get URL of tab 1
make new tab with properties {
URL:"https://www.apple.com.cn"}
end tell
end tell
end applicationWillFinishLaunching_
编译运行后回在控制台报错:*** -[AppDelegate applicationWillFinishLaunching:]: Not authorized to send Apple events to Safari. (error -1743)
是因为App还没有获取到发送AppleScript事件的用户权限,所以不能直接控制Safari打开网页,在Xcode工程中的info.plist中添加Privacy - AppleEvents Sending Usage Description,后面添加上描述,再次启动就会弹出授权弹框。
最终AppDelegate.applescript文件完整示例代码
script AppDelegate
property parent : class "NSObject"
-- 载入OC类
property Test : class "Test"
-- IBOutlets
property theWindow : missing value
on applicationWillFinishLaunching_(aNotification)
-- Insert code here to initialize your application before any files are opened
--Safari打开网页
tell application "Safari"
activate
--新建tab页,传入URL
tell front window
--get every tab
--get URL of tab 1
make new tab with properties {
URL:"https://www.apple.com.cn"}
end tell
end tell