oligofren oligofren - 2 months ago 18
AppleScript Question

Bring Chrome started from script to front

I am wondering how I can launch a fresh new Chrome instance (see my script below) that will be brought to the front. Currently the shell script opens the new Chrome instance in the background, which is less than optimal. Executing the shell script from Applescript does nothing to remedy this.

The interesting thing is that if I open Chrome using a shell command directly from AppleScript it seems to open in the foreground:

set q to "'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --user-data-dir=/tmp/1234"
do shell script q


Applescript

do shell script "~/bin/chrome-fresh"


Shell script

#!/bin/sh
# This is quite useful for front-enders, as it will launch a fresh
# Chrome instance with no loaded plugins or extensions that messes
# with your performance profiling or network debugging
#
# Install:
# install -m 555 ~/Downloads/chrome-fresh /usr/local/bin/

CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
ARGS="$@"

# make a fresh user directory
TMP_USERDIR=$(mktemp -d);

# avoid the dialog on the first startup
touch "$TMP_USERDIR/First Run";

# start chrome using a fresh user directory
"$CHROME" --user-data-dir="$TMP_USERDIR" "$ARGS"

Answer

Run the command in background (put the & at the end of the command).

Use $! to get the process ID of the last command

# start chrome using a fresh user directory
"$CHROME" --activate-on-launch --user-data-dir="$TMP_USERDIR" "$ARGS" &
chromePid=$!
sleep 2
# bring Chrome 
osascript -e 'tell application "System Events"' -e "tell (first process whose its unix id is \"$chromePid\" ) to set frontmost to true" -e 'end tell'