Chen-Tai
Chen-Tai

Reputation: 3473

MacOS app run Applescript to execute keystroke on other application

I have a question about running applescript in MacOS app.

I would like to create a Mac App and it can execute an Applescript to copy the selected text on Chrome.

Here is the 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

The idea is I save this Applescript in the distributed Mac App and let the app to execute this script.

In development env (before compiled to {Appname}.app), it can successfully switch to Chrome and copy the selected text.

However, after bundling it as an {Appname}.app, it can activate Chrome if it has not run yet, but it cannot execute the Command + C keyboard combination.

My guess is the app didn't ask the Accessibility in Security Setting, so I add it and turn it on. But it still can't work.

I've also tried to add the entitlement setting, but still failed:

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

Does anyone know the possible solution?

I am the newbie of Mac App development. Any hint is very welcome. Thanks!

Upvotes: 0

Views: 584

Answers (1)

wch1zpink
wch1zpink

Reputation: 3142

Google Chrome actually has a copy selection command. No need to bring system events into the equation.

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

Or you can just insert this following handler into your code (I prefer adding mine towards the bottom of my script)

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

Then anytime you want to run that handler, just call it by using this line of code (inserting the application name instead of my example of TextEdit)

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

Upvotes: 2

Related Questions