如何在谷歌浏览器或Microsoft Edge上打开标签2(如果不存在)?



我是AppleScript的新手,尝试了AppleScript解决方案来打开选项卡并加载网页:

tell application "Google Chrome"   -- or "Microsoft Edge"
tell window 1
tell tab 2
set URL to "https://google.com/"
end tell
end tell
end tell

但如果标签2不存在,它就不会有任何作用。

然后我试图通过检查任何选项卡中是否存在URL来解决这个问题:

tell application "Google Chrome"
repeat with w in windows
set i to 1
repeat with t in tabs of w
if URL of t starts with "https://mail.google" then
set active tab index of w to i
set index of w to 1
return
end if
set i to i + 1
end repeat
end repeat
open location "https://mail.google.com/mail/u/0/#inbox"
end tell

但这有点过头了,它打开了一个新的选项卡,而不是打开一个选项卡2。

然后我尝试了

tell application "Google Chrome"   -- or "Microsoft Edge"
tell window 1
open tab 2     -- added this line
tell tab 2
set URL to "https://google.com/"
end tell
end tell
end tell

但无论是open tab 2activate tab 2还是start tab 2,都不起作用。我们如何让它发挥作用,一般来说,如何找出我们可以使用的词汇或动词?

open tab 2就是问题所在。如果存在浏览器窗口,并且您希望创建一个新的选项卡并设置其URL,则:

tell application "Google Chrome" to ¬
if exists front window then ¬
make new tab at end of ¬
tabs of front window ¬
with properties ¬
{URL:"https://www.example.com"}

如果存在浏览器窗口,并且您想更改tab 2URL,则:

tell application "Google Chrome" to ¬
if exists front window then ¬
tell front window to ¬
if (exists tab 2) then ¬
tell its tab 2 to ¬
set its URL to ¬
"https://www.example.com"

备注:

  • 示例AppleScript代码也适用于Microsoft Edge
  • 使用if语句可以将这些示例扩展为正常的格式,以确定Google Chrome和/或Microsoft Edge是否存在或已经在运行,以及是否正在运行窗口等。您只需要根据需要对其进行编码即可
  • 查看AppleScript语言指南
  • 脚本编辑器中,查看任何应用程序AppleScript字典的,以便为其编写代码。从窗口菜单库⇧⌘L

下面的示例AppleScript代码显示了一个为Google ChromeMicrosoft Edge的存在进行编码的示例,以及当您可以根据条件编写代码时,它们是否正在运行。正如所写的,它支持谷歌Chrome,但如果它确实存在,那么微软边缘将运行其代码。要支持Microsoft Edge,请更改主if语句结构以适应。

tell application "System Events"
set existsGoogleChrome to exists file "/Applications/Google Chrome.app"
set existsMicrosoftEdge to exists file "/Applications/Microsoft Edge.app"
end tell
if existsGoogleChrome then
if running of application "Google Chrome" then
tell application "Google Chrome"
# Do Something
end tell
else
tell application "Google Chrome"
# Do Something Else
end tell
end if
else
if existsMicrosoftEdge then
if running of application "Microsoft Edge" then
tell application "Microsoft Edge"
# Do Something
end tell
else
tell application "Microsoft Edge"
# Do Something Else
end tell
end if
end if
end if

最新更新