AppleScript browser tab weirdness
September 19, 2011 at 11:21 PM by Dr. Drang
I was playing around with an AppleScript tonight and ran into an odd bug when trying to write a script that worked whether my default browser was Safari or Chrome. It happens when I use a variable to hold the browser’s application ID—com.google.chrome
, for example—and try to access any information about its tabs.
For example, this
set browser to "com.google.chrome"
tell application id browser
get active tab index of front window
end tell
won’t compile. It throws a syntax error at the word tab
and says
Expected end of line but found property.
I get a similar thing when I try this
set browser to "com.apple.Safari"
tell application id browser
get URL of tab 1 of front window
end tell
In this case, the syntax error is at the 1
, and the error message is
Expected end of line but found number.
Since both this
tell application id "com.google.chrome"
get active tab index of front window
end tell
and this
tell application id "com.apple.Safari"
get URL of tab 1 of front window
end tell
compile and run just fine, you might think the problem lies with using a variable to hold the application ID instead of using a string literal. But you’d be wrong, because this
set browser to "com.google.chrome"
tell application id browser
get bounds of front window
end tell
and this
set browser to "com.apple.Safari"
tell application id browser
get visible of front window
end tell
both work even though I’m using a variable. Window properties like visible
, name
, id
, and zoomable
work regardless of whether I use a variable or a literal, but tab properties only work with a literal.
In the script I’m noodling with, the browser
variable isn’t set by a simple assignment as in these examples, it’s set according to the user’s default browser. I can certainly get around the bug by doing something like this
if browser is "com.google.chrome"
tell application "Google Chrome"
<whatever>
end tell
else
if browser is "com.apple.Safari"
tell application "Safari"
<whatever>
end tell
end if
end if
but I was hoping to write something that was a little less clumsy and redundant. The Chrome and Safari AppleScript libraries are enough alike that you can often use the same code for either, and I was hoping to take advantage of that by doing something clever and sleek, like
tell application id browser
set theURL to URL of tab n of front window
end tell
Sadly, this simplicity isn’t to be.