关闭Chrome窗口后AppleScript回退命令报错"can't get window 1"求助
Hey there, let’s work through that frustrating error you’re seeing when adding repeated "Go back" commands to your AppleScript. The "can't get window 1" issue usually pops up because Chrome’s state changes between your script’s initial check and repeated execution—like if a window closes when you back out of the last tab, or Chrome’s window reference gets invalidated mid-run.
Here’s a refined version of your script that addresses these edge cases, plus breakdowns of the key fixes:
tell application "Google Chrome" -- First, confirm Chrome is actually running if running then -- Check for open windows *right before* trying to interact if (count of windows) > 0 then try -- Make sure the active tab actually has history to go back to if can go back of active tab of window 1 then go back of active tab of window 1 else -- Optional: Alert if there's no history to back into display dialog "No more back history for this tab!" buttons {"OK"} default button 1 end if on error errMsg number errNum -- Catch unexpected errors (like a window closing mid-execution) display dialog "Oops, something went wrong: " & errMsg & " (" & errNum & ")" buttons {"OK"} default button 1 end try else display dialog "Chrome has no open windows to navigate!" buttons {"OK"} default button 1 end if else display dialog "Chrome isn't running right now!" buttons {"OK"} default button 1 end if end tell
Key Improvements for High Sierra:
- Real-time window check: Instead of only verifying windows at the start, we check
count of windows > 0immediately before trying to access window 1. This handles cases where a window closes between repeated script runs. - History validation: The
can go back of active tabcheck prevents trying to back out of a tab with no browsing history (like a newly opened blank tab), which can trigger unexpected window closures. - Error handling: The
try...on errorblock catches sudden state changes (like manually closing a window while the script runs) and gives you a clear error message instead of a vague "can't get window 1" prompt.
If you’re triggering this script repeatedly (via a shortcut or timer), make sure to leave a small delay between executions—High Sierra’s Chrome can be slow to update its AppleScript state, so rushing commands can lead to race conditions.
内容的提问来源于stack exchange,提问作者Josiah Holgate

