MacOS 应用程序 运行 Applescript 在其他应用程序上执行击键

MacOS app run Applescript to execute keystroke on other application

我对 MacOS 应用程序中的 运行ning applescript 有疑问

我想创建一个 Mac 应用程序,它可以执行一个 Applescript 来复制 Chrome 上的选定文本。

这是 Applescript:

tell application "Google Chrome"
    activate
    try
        tell application "System Events"
            keystroke "c" using {command down}
        end tell
    on error
        display dialog "error" buttons {"OK"}
    end try
end tell

delay 1
set selectedText to the clipboard

我的想法是将这个 Applescript 保存在分布式 Mac 应用程序中,让应用程序执行这个脚本。

在开发环境(编译为{Appname}.app之前),可以成功切换到Chrome并复制选中的文本。

但是打包为{Appname}.app后,如果还没有运行可以激活Chrome,但是不能执行Command + C组合键。

我猜是应用程序没有询问 Accessibility in Security Setting,所以我添加并打开了它。但是还是不行。

我也试过添加entitlement设置,但还是失败了:

<key>com.apple.security.temporary-exception.apple-events</key>
<array>
   <string>com.google.Chrome</string>
   <string>com.apple.systemevents</string>
</array>

有谁知道可能的解决方案吗?

我是Mac应用程序开发的新手。任何提示都非常受欢迎。谢谢!

Google Chrome其实有复制选择命令。无需将系统事件纳入等式。

if application "Google Chrome" is running then
    set the clipboard to ""
    tell application "Google Chrome"
        tell active tab of window 1
            copy selection
        end tell
    end tell
    set selectedText to the clipboard
end if

或者您可以将以下处理程序插入您的代码中(我更喜欢将我的添加到脚本底部)

to copySelection(theApp)
    set the clipboard to ""
    activate application theApp
    repeat while application theApp is not frontmost
        delay 0.2
    end repeat
    tell application "System Events"
        tell application process theApp
            keystroke "c" using {command down}
        end tell
    end tell
    set selectedText to (the clipboard)
end copySelection

然后任何时候你想要 运行 该处理程序,只需使用这行代码调用它(插入应用程序名称而不是我的 TextEdit 示例)

copySelection("TextEdit") -- Replace With Your Desired App