使用变量指定应用时无法设置AppleScript窗口miniaturized属性
I’ve run into this exact issue before—let’s break down why it happens and how to fix it quickly.
The Root Cause
AppleScript relies on compile-time term binding when working with applications. When you hardcode tell application "Safari", the compiler loads Safari’s script dictionary during compilation, so it knows exactly what miniaturized means. But when you use a variable like tell application x, the compiler can’t resolve which app’s dictionary to use upfront. At runtime, it throws that "-1700" error because it doesn’t recognize the miniaturized term for the target app.
Solutions That Work
1. Reference the Application by Its ID (Most Reliable)
Every macOS app has a unique bundle ID that doesn’t change even if the app name is localized or renamed. For Safari, it’s com.apple.Safari. Use this instead of the app name variable:
set appID to "com.apple.Safari" -- Replace with your app's bundle ID tell application id appID to set miniaturized of front window to false
To find an app’s bundle ID:
- Right-click the app in Finder → Get Info, or
- Run
mdls -name kMDItemCFBundleIdentifier /Applications/YourApp.appin Terminal.
2. Assign the App to a Variable First
Instead of passing the variable directly to tell application, first fetch the application object. This forces AppleScript to resolve the app’s dictionary at runtime:
set appName to "Safari" set targetApp to application appName tell targetApp set miniaturized of front window to false -- Add other operations for the app here if needed end tell
This is great if you need to run multiple commands on the same app—cleaner than repeating the app reference.
3. Use run script to Dynamically Compile Code
If you need a quick one-liner for simple operations, generate a script string with your variable and execute it dynamically. This compiles the targeted code at runtime, so the term binds correctly:
set appName to "Safari" run script "tell application \"" & appName & "\" to set miniaturized of front window to false"
Note: Be careful with string escaping if your app name has quotes (though most app names don’t). This method is less ideal for complex scripts since it’s harder to read and maintain.
Which to Choose?
- Bundle ID: Best for stability, especially if your script needs to work across localized systems.
- App Object Variable: Cleanest for multi-operation workflows.
- Dynamic
run script: Quick fix for single-line tasks.
内容的提问来源于stack exchange,提问作者Kashyap

