applescript:如何在多个 windows 中执行击键

applescript: how to execute keystroke in several windows

我需要在某些应用程序(例如 safari 浏览器)中通过 applescript 执行一些击键(例如,cmd + t 以创建新选项卡)。所以,我写了一个代码:

tell application "Safari" to activate
tell application "Safari"
    set wList to every window whose visible is true

    repeat with app_window in wList
        log app_window
        set index of app_window to 1
        tell application "System Events"
            keystroke "t" using {command down}
        end tell
        delay (1)
    end repeat
end tell

我希望此代码在每个打开的 safari 浏览器中打开一个新选项卡 window。但实际上,此代码只是在第一个活动的 safari window 中打开 n 个新选项卡,其中 n - 是打开的 safari windows 的计数。似乎我在这一行中更改焦点时遇到问题:

set index of app_window to 1

那么,如何正确更改焦点以在每个 window 中执行击键?

UPD

有趣的事情 - 此代码可与 Finder 应用程序一起正常工作(只需替换 Safari -> Finder),但不适用于 Safari 和 ios 模拟器 (Xcode)

UPD

此外,它不适用于 Google Chrome - 我遇到了相同的行为。

如果你想为Safari中的所有windows添加一个新的tab,那么在这里是如何做到的:

示例 AppleScript 代码:

tell application "Safari"
    set myWindows to a reference to windows
    repeat with thisWindow in myWindows
        make new tab at end of tabs of thisWindow
    end repeat
end tell 

备注:

您可以将 at end of tabs 更改为其他位置,即:

[at location specifier] : The location at which to insert the object.

例如:at beginning of tabs


更新地址评论:

示例 AppleScript 代码:

tell application "Safari"
    activate
    set myWindows to ¬
        (windows whose visible is true)
    repeat with thisWindow in myWindows
        set winName to name of thisWindow
        my addNewTab(winName)
        --  # Do other stuff here.
        
    end repeat
end tell

to addNewTab(winName)
    tell application "System Events"
        perform action "AXRaise" of ¬
            window winName of process "Safari"
        delay 0.5
        keystroke "t" using command down
    end tell
end addNewTab
  



注意:示例 AppleScript code 就是这样,没有包含任何 错误处理 不包含任何额外的 错误处理 可能是适当的。用户有责任根据需要或需要添加任何 错误处理 。查看 try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay 命令 在适当的事件之间可能是必要的,例如delay 0.5,适当设置延迟

你不能直接控制windows的索引,因为属性indexread/only.但是你可以在 Safari.app:

的帮助下完成
tell application "Safari"
    activate
    set wList to every window whose visible is true
    repeat with aWindow in wList
        tell application "System Events" to keystroke "t" using command down
        set miniaturized of aWindow to true
        delay 1
    end repeat
    repeat with aWindow in wList
        set miniaturized of aWindow to false
    end repeat
end tell

注意:您可以使用 visible 属性 代替 miniaturized 属性(无需延迟):

tell application "Safari"
    activate
    set wList to every window whose visible is true
    repeat with aWindow in wList
        tell application "System Events" to keystroke "t" using command down
        set visible of aWindow to false
    end repeat
    repeat with aWindow in wList
        set visible of aWindow to true
    end repeat
end tell