Services bug that prematurely activates an application

Solution 1:

The only workaround I've found after testing several different scenarios is to wrap the Safari commands within a do shell script command, e.g. do shell script "osascript -e 'tell application \"Safari\" to activate'". Note that with osascript, multiple −e options may be given to build up a multi-line script.

From the manual page for osascript:

−e statement

Enter one line of a script. If −e is given, osascript will not look for a filename in the argument list. Multiple −e options may be given to build up a multi-line script. Because most scripts use characters that are special to many shell programs (e.g., AppleScript uses single and double quote marks, “(”, “)”, and “*”), the statement will have to be correctly quoted and escaped to get it past the shell intact.

Example AppleScript code:

tell application "Safari"
    activate
    make new document in front
    set URL of front document to "http://apple.stackexchange.com/questions/271133/services-bug-that-prematurely-activates-an-application"
end tell

An example of the AppleScript code above, written as a do shell script command using osascript with the -e option, as necessary.

do shell script "osascript -e 'tell application \"Safari\"' -e 'activate' -e 'make new document in front' -e 'set URL of front document to \"http://apple.stackexchange.com/questions/271133/services-bug-that-prematurely-activates-an-application\"' -e 'end tell'"

As you can see, each line of AppleScript code from the normal tell block statement is its own -e option, and as noted in the manual page for osascript with the -e option, escaping with a backslash has been done as necessary for the code to compile correctly before being run.

In other words, this turn the normal tell block statement and its included commands to a one-line do shell script command so as to circumvent the apparent bug in the use case scenario presented in the OP.

Note that you should be able to do similar with other applications triggered by the same bug, by substituting the appropriate application name (and commands) as needed.