求可从命令行运行的AppleScript:获取活跃应用信息及浏览器URL
命令行可运行的AppleScript解决方案
我给你写了一个能直接从终端启动的AppleScript,完美满足你要获取当前活跃应用信息的需求,一起来看看吧!
完整脚本代码
你可以直接复制下面的代码,用osascript命令执行,或者保存为.scpt文件后运行:
set appInfo to "" -- 获取当前活跃应用 tell application "System Events" set frontApp to name of first application process whose frontmost is true end tell -- 获取窗口标题 tell application frontApp try set windowTitle to name of front window on error set windowTitle to frontApp end try end tell -- 处理浏览器的URL获取 set browserApps to {"Google Chrome", "Safari", "Firefox", "Brave", "Edge"} if frontApp is in browserApps then tell application frontApp try set tabURL to URL of active tab of front window on error set tabURL to "" end try end tell else set tabURL to "" end if -- 拼接结果,用分号分隔 set appInfo to frontApp & "; " & windowTitle & "; " & tabURL -- 输出结果 return appInfo
运行方式
方式一:直接在终端执行
把上面的代码转换成单行命令,直接在终端输入即可运行:
osascript -e 'set appInfo to ""' -e 'tell application "System Events" to set frontApp to name of first application process whose frontmost is true' -e 'tell application frontApp' -e 'try' -e 'set windowTitle to name of front window' -e 'on error' -e 'set windowTitle to frontApp' -e 'end try' -e 'end tell' -e 'set browserApps to {"Google Chrome", "Safari", "Firefox", "Brave", "Edge"}' -e 'if frontApp is in browserApps then' -e 'tell application frontApp' -e 'try' -e 'set tabURL to URL of active tab of front window' -e 'on error' -e 'set tabURL to ""' -e 'end try' -e 'end tell' -e 'else' -e 'set tabURL to ""' -e 'end if' -e 'set appInfo to frontApp & "; " & windowTitle & "; " & tabURL' -e 'return appInfo'
方式二:保存为脚本文件运行
- 打开Mac自带的「脚本编辑器」,粘贴上面的代码,将文件保存为
GetActiveAppInfo.scpt - 在终端中执行以下命令(替换成你实际的文件路径):
osascript /Users/你的用户名/Documents/GetActiveAppInfo.scpt
示例返回效果
- 当活跃应用是Google Chrome且打开Stack Overflow标签页时:
Google Chrome; AppleScript: How to get URL of Safari tab which failed to load? - Stack Overflow; https://stackoverflow.com/ - 当活跃应用是iTunes时:
iTunes; iTunes; - 当活跃应用是iTerm2时:
iTerm2; 1. node test.js (sleep); - 当活跃应用是Safari且打开GitHub页面时:
Safari; GitHub; https://github.com/
内容的提问来源于stack exchange,提问作者Tomasz Giba
相关产品推荐
相关产品推荐

