MacOS – How to use variable in AppleScript for name of browser

applescriptmacos

I'm trying to streamline an AppleScript which monitors whether tabs in web browsers are currently open to specific sites.

I can repeat the same block of code multiple times, clunky but it works:

tell application "Safari"
    repeat with site in sitelist
        repeat with w from 1 to number of windows
            set tabList to (every tab of window w whose URL contains site)
        end repeat
    end repeat
end tell
tell application "Chrome"
    repeat with site in sitelist
        repeat with w from 1 to number of windows
            set tabList to (every tab of window w whose URL contains site)
        end repeat
    end repeat
end tell

I'd like this code to work for more browsers than just these two. I've tried using a variable to represent the browser name:

set browserlist to {"Safari", "Chrome"}

repeat with browser in browserlist
    tell application browser
        repeat with site in sitelist
            repeat with w from 1 to number of windows
                set tabList to (every tab of window w whose URL contains site)
            end repeat
        end repeat
    end tell
end repeat

But AppleScript gives me a syntax error, "Expected class name but found property."
Apparently when I change tell application "Safari" to tell application browser, it has a problem with tab in this line:

set tabList to (every tab of window w whose URL contains site)

Can I get tab to work with the variable browser?

Thanks!

Best Answer

That won’t work because the target for an application tell statement is needed at compile time to load its scripting dictionary. An application’s terminology is defined however the developer wants it, so anything similar between applications is more of an accident than any kind of convention.

The closest you are going to get would be to programmatically build a script as a text string and use it with a run script statement, since the script in the string is compiled when it is used:

set theApp to "Safari"
set theScript to "tell application \"" & theApp & "\" to get tabs of window 1"
run script theScript