使用Applescript自动化Safari:基于URL智能切换到已打开的选项卡
我正在尝试使用听写功能,通过语音命令自动化我的Mac电脑。我有以下简单的脚本,即使Safari关闭,它也会用url打开一个新的Safari选项卡:使用Applescript自动化Safari:基于URL智能切换到已打开的选项卡,safari,applescript,Safari,Applescript,我正在尝试使用听写功能,通过语音命令自动化我的Mac电脑。我有以下简单的脚本,即使Safari关闭,它也会用url打开一个新的Safari选项卡: tell application "Safari" activate end tell set theUrl to "https://mail.google.com/mail/u/0/#inbox" tell application "Safari" if not (exists current tab of front win
tell application "Safari"
activate
end tell
set theUrl to "https://mail.google.com/mail/u/0/#inbox"
tell application "Safari"
if not (exists current tab of front window) then make new document -- if no window
tell front window
set current tab to (make new tab at end of tabs with properties {URL:theUrl})
end tell
end tell
它工作得很好。我可以说“Mac,打开Gmail”,它会突然打开。不过,我想看看是否可以改进脚本,让脚本确定某个站点是否已在另一个选项卡中打开,如果已打开,则切换到该现有选项卡。有没有办法获取包含我想要的URL的第一个选项卡的编号?好极了,多亏了我的脚本天才,我有了一个解决方案。为了实现这一点,我稍微修改了脚本。以下是最终结果:
if application "Safari" is running then
tell application "Safari"
activate
end tell
else
tell application "Safari"
activate
delay 5
end tell
end if
set searchpat to "mail.google"
set theUrl to "https://mail.google.com/mail/u/0/#inbox"
tell application "Safari"
set winlist to every window
set winmatchlist to {}
set tabmatchlist to {}
set tabnamematchlist to {}
repeat with win in winlist
set ok to true
try
set tablist to every tab of win
on error errmsg
--display dialog name of win as string
set ok to false
end try
if ok then
repeat with t in tablist
if searchpat is in (name of t as string) then
set end of winmatchlist to win
set end of tabmatchlist to t
set end of tabnamematchlist to (id of win as string) & "." & (index of t as string) & ". " & (name of t as string)
--display dialog name of t as string
else if searchpat is in (URL of t as string) then
set end of winmatchlist to win
set end of tabmatchlist to t
set end of tabnamematchlist to (id of win as string) & "." & (index of t as string) & ". " & (name of t as string)
--display dialog name of t as string
end if
end repeat
end if
end repeat
if (count of tabmatchlist) = 1 then
--display dialog "one!"
set w to item 1 of winmatchlist
set t to item 1 of tabmatchlist
set current tab of w to t
set index of w to 1
else if (count of tabmatchlist) = 0 then
if not (exists current tab of front window) then make new document -- if no window
tell front window
set current tab to (make new tab at end of tabs with properties {URL:theUrl})
end tell
else
set whichtab to choose from list of tabnamematchlist with prompt "The following tabs match, please select one:"
set AppleScript's text item delimiters to "."
if whichtab is not equal to false then
set tmp to text items of (whichtab as string)
set w to (item 1 of tmp) as integer
set t to (item 2 of tmp) as integer
set current tab of window id w to tab t of window id w
set index of window id w to 1
end if
end if
end tell