Last active
September 28, 2023 15:37
-
-
Save Lawrencium77/354f0eac8f6ab58811c70e68fa0049ba to your computer and use it in GitHub Desktop.
Apple Script to open ChatGPT - useful for an Alfred Workflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Establish whether Chrome is already open or not | |
tell application "System Events" | |
set isRunning to (name of processes) contains "Google Chrome" | |
end tell | |
-- Count the number of open windows. This is useful later on. | |
tell application "Google Chrome" | |
set windowCount to count windows | |
end tell | |
tell application "Google Chrome" | |
set targetURL to "https://chat.openai.com" -- Desired URL | |
set NumberOfWindows to (count of (every window where visible is true)) -- Get window count | |
if isRunning is false then | |
-- If Chrome isn't running, launch it, wait, and open a tab with target URL | |
launch | |
delay 0.5 -- give some time for Chrome to open its default window | |
set URL of active tab of front window to targetURL | |
return | |
else if windowCount = 0 then | |
-- If Chrome is running but there are no open windows, create a new window | |
make new window | |
-- Set the URL of the active tab of the new window to the target URL | |
delay 0.5 -- give some time for Chrome to open its default window | |
set URL of active tab of front window to targetURL | |
activate | |
return | |
end if | |
set tabFound to false | |
set targetWindow to missing value | |
set targetTabIndex to missing value | |
set emptyTab to missing value | |
-- Loop through all windows and tabs to find the target URL or an empty tab | |
repeat with aWindow in every window | |
set tabIndex to 0 | |
repeat with aTab in every tab of aWindow | |
set tabIndex to tabIndex + 1 | |
if (URL of aTab) contains targetURL then | |
set tabFound to true | |
set targetWindow to aWindow | |
set targetTabIndex to tabIndex | |
exit repeat | |
else if (URL of aTab) is "about:blank" or (URL of aTab) contains "chrome://newtab" then | |
set emptyTab to aTab | |
end if | |
end repeat | |
if tabFound then exit repeat | |
end repeat | |
if tabFound then | |
-- Activate the window and the tab with the target URL | |
set active tab index of targetWindow to targetTabIndex | |
activate targetWindow | |
else if emptyTab is not missing value then | |
-- If an empty tab is found, use it to open the target URL | |
set URL of emptyTab to targetURL | |
activate | |
else | |
-- If the URL isn't open and no empty tab is available, create a new tab with the target URL | |
tell front window | |
make new tab with properties {URL:targetURL} | |
activate | |
end tell | |
end if | |
end tell |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment