【问题标题】:MacOS app run Applescript to execute keystroke on other applicationMacOS 应用程序运行 Applescript 以在其他应用程序上执行击键
【发布时间】:2019-02-01 06:54:38
【问题描述】:

我有一个关于在 MacOS 应用程序中运行 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 App 中,让应用程序执行这个脚本。

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

但是,将其捆绑为{Appname}.app后,如果Chrome尚未运行,则可以激活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 App 开发的新手。任何提示都非常受欢迎。谢谢!

【问题讨论】:

    标签: macos applescript


    【解决方案1】:

    谷歌浏览器实际上有一个复制选择命令。无需将系统事件纳入方程式。

    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
    

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2017-08-18
      相关资源
      最近更新 更多