├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── img
├── open-private-window.png
├── open-safari-window-url.png
├── open-safari-window.png
├── safari-icon.png
├── stp.png
├── sw.png
├── swp.png
└── swt.png
└── src
├── focus_tab.js
├── list_tabs.js
├── list_tabs.zsh
├── new_private_window.zsh
├── new_window.zsh
├── tab_to_private.js
└── tab_to_private.zsh
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: vanstrouble
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
14 | thanks_dev: # Replace with a single thanks.dev username
15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2025 Pedro Vázquez
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #
Safari Control | Alfred Workflow
2 |
3 | Open new Safari windows anywhere, sneak into private browsing, switch profiles like you’re hiding something, and zip through tabs like your boss is walking in.
4 |
5 | ## Download
6 |
7 | - Available on the Alfred Gallery. Get it [here](https://alfred.app/workflows/vanstrouble/safari-control/).
8 | - You can also download it from GitHub [here](https://github.com/vanstrouble/new-safari-window-alfred-workflow/releases).
9 |
10 | ## Usage
11 |
12 | ### New window (sw)
13 |
14 |
15 |
16 | Opens a new Safari window in the current space. By default, pressing the **Command** key will open a **new private window**.
17 |
18 | #### Examples:
19 |
20 | | Command | Description |
21 | |-----------------|-----------------------------------------------------------------------------|
22 | | `sw` | Opens a new Safari window in the current space. |
23 | | `sw x3` | Opens 3 new Safari windows in the current space. |
24 | | `sw URL` | Opens a new Safari window with the specified URL. |
25 | | `sw + Command (⌘)` | Opens a new tab in the current Safari window instead of creating a window. |
26 |
27 | ### Open Safari window profiles (swp)
28 |
29 |
30 |
31 | List and open Safari windows using up to 3 customizable profiles (e.g., work, personal, testing). Use `sw p[number]` to instantly open a new Safari window with the selected profile.
32 |
33 | #### Examples:
34 |
35 | | Command | Description |
36 | |-----------------|-----------------------------------------------------------------------------|
37 | | `swp` | Lists available profiles (Profile 1, Profile 2, Profile 3). |
38 | | `sw p1` | Opens a new Safari window using Profile 1. |
39 | | `sw p2` | Opens a new Safari window using Profile 2. |
40 | | `sw p3` | Opens a new Safari window using Profile 3. |
41 |
42 | ### List Safari tabs (swt)
43 |
44 |
45 |
46 | Browse all open Safari tabs and search by title or URL to instantly bring the one you need into focus.
47 |
48 | ### Open current tab in private mode (stp)
49 |
50 |
51 |
52 | Extracts the current tab (the one you are currently viewing) and opens it in a new private browsing window.
53 |
54 | ## Customization
55 |
56 | Customize the workflow to fit your style: change the default keywords, assign hotkeys to trigger actions instantly, and rename the default profiles to match your Safari setup. All settings can be adjusted directly in Alfred during or after installation.
57 |
58 | ## Acknowledgments
59 |
60 | - This workflow is inspired in [Caio Gondim's one](https://github.com/caiogondim/alfred-chrome-window-workflow?tab=readme-ov-file)
61 |
--------------------------------------------------------------------------------
/img/open-private-window.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/open-private-window.png
--------------------------------------------------------------------------------
/img/open-safari-window-url.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/open-safari-window-url.png
--------------------------------------------------------------------------------
/img/open-safari-window.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/open-safari-window.png
--------------------------------------------------------------------------------
/img/safari-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/safari-icon.png
--------------------------------------------------------------------------------
/img/stp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/stp.png
--------------------------------------------------------------------------------
/img/sw.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/sw.png
--------------------------------------------------------------------------------
/img/swp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/swp.png
--------------------------------------------------------------------------------
/img/swt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vanstrouble/safari-control-alfred-workflow/38e790f5452625627e1a6ed5330b038ddb9a8871/img/swt.png
--------------------------------------------------------------------------------
/src/focus_tab.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env osascript -l JavaScript
2 |
3 | function run(argv) {
4 | const targetUrl = argv[0];
5 |
6 | try {
7 | const safari = Application("Safari");
8 |
9 | // Ensure Safari is running
10 | if (!safari.running()) {
11 | safari.activate();
12 | delay(0.5);
13 | }
14 |
15 | let foundTab = false;
16 | let foundWindow = null;
17 |
18 | // Search in all windows and tabs
19 | for (let i = 0; i < safari.windows.length; i++) {
20 | const window = safari.windows[i];
21 |
22 | // Verify that the window has tabs
23 | if (!window.tabs || window.tabs.length === 0) continue;
24 |
25 | for (let j = 0; j < window.tabs.length; j++) {
26 | const tab = window.tabs[j];
27 | const url = tab.url() || "";
28 |
29 | // Compare URLs
30 | if (url === targetUrl) {
31 | // Set this tab as active
32 | window.currentTab = tab;
33 | foundTab = true;
34 | foundWindow = window;
35 | break;
36 | }
37 | }
38 |
39 | if (foundTab) break;
40 | }
41 |
42 | // If we found the tab, activate Safari and bring the window to the front
43 | if (foundTab && foundWindow) {
44 | // Activate Safari first
45 | safari.activate();
46 |
47 | // Simply make the window the frontmost window without toggling visibility
48 | foundWindow.index = 1; // This makes the window the frontmost window
49 |
50 | return "Tab focused successfully";
51 | } else {
52 | // If we didn't find the tab, open the URL in a new tab
53 | safari.activate();
54 | safari.openLocation(targetUrl);
55 | return "URL opened in a new tab";
56 | }
57 | } catch (e) {
58 | return `Error: ${e.message}`;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/list_tabs.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env osascript -l JavaScript
2 |
3 | function run() {
4 | if (!Application("Safari").running()) {
5 | return JSON.stringify({
6 | items: [{
7 | title: "Safari is not running",
8 | subtitle: "Press enter to launch Safari",
9 | valid: false
10 | }]
11 | });
12 | }
13 |
14 | try {
15 | const safari = Application("Safari");
16 | const tabsMap = new Map();
17 | const windowCount = safari.windows.length;
18 |
19 | // Predefined regular expressions
20 | const protocolRegex = /(^\w+:|^)\/\//;
21 | const nonWordRegex = /[^\w]/g;
22 |
23 | // A single loop to process all tabs
24 | for (let i = 0; i < windowCount; i++) {
25 | const window = safari.windows[i];
26 | let windowIndex;
27 |
28 | try {
29 | windowIndex = window.index();
30 | } catch (e) {
31 | windowIndex = i + 1;
32 | }
33 |
34 | if (!window.tabs || window.tabs.length === 0) continue;
35 |
36 | const tabsLength = window.tabs.length;
37 |
38 | for (let j = 0; j < tabsLength; j++) {
39 | // Process the tab using the helper function
40 | const tabData = getTabData(window, j, windowIndex, protocolRegex, nonWordRegex);
41 | if (!tabData) continue;
42 |
43 | const { url, data } = tabData;
44 |
45 | // If we already processed this URL, just increment the counter
46 | if (tabsMap.has(url)) {
47 | const existingData = tabsMap.get(url);
48 | existingData.count++;
49 | tabsMap.set(url, existingData);
50 | } else {
51 | // Save new entry in the map
52 | tabsMap.set(url, data);
53 | }
54 | }
55 | }
56 |
57 | // Create final array of items
58 | const items = Array.from(tabsMap.values()).map(data => {
59 | const item = data.item;
60 | if (data.count > 1) {
61 | item.subtitle = `${item.subtitle} (${data.count} tabs)`;
62 | }
63 | return item;
64 | });
65 |
66 | // If there are no tabs
67 | if (items.length === 0) {
68 | return JSON.stringify({
69 | items: [{
70 | title: "No tabs found",
71 | subtitle: "No open tabs in Safari",
72 | valid: false
73 | }]
74 | });
75 | }
76 |
77 | return JSON.stringify({ items });
78 | } catch (e) {
79 | return JSON.stringify({
80 | items: [{
81 | title: "Error",
82 | subtitle: "Failed to get Safari tabs: " + e.message,
83 | valid: false
84 | }]
85 | });
86 | }
87 | }
88 |
89 | // Helper function to process tab data
90 | function getTabData(window, tabIndex, windowIndex, protocolRegex, nonWordRegex) {
91 | try {
92 | const tab = window.tabs[tabIndex];
93 | const title = tab.name() || "";
94 | const url = tab.url() || "about:blank";
95 |
96 | // Process URL
97 | const matchUrl = url.replace(protocolRegex, "");
98 | let decodedUrl;
99 |
100 | try {
101 | decodedUrl = decodeURIComponent(matchUrl);
102 | } catch (e) {
103 | decodedUrl = matchUrl;
104 | }
105 |
106 | const cleanUrl = decodedUrl.replace(nonWordRegex, " ");
107 | const matchString = `${title} ${cleanUrl}`;
108 |
109 | return {
110 | url,
111 | data: {
112 | count: 1,
113 | item: {
114 | uid: `${windowIndex}-${tabIndex + 1}`,
115 | title: title,
116 | subtitle: url,
117 | arg: url,
118 | match: matchString,
119 | icon: { path: "./icon.png" },
120 | quicklookurl: url
121 | }
122 | }
123 | };
124 | } catch (e) {
125 | return null;
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/src/list_tabs.zsh:
--------------------------------------------------------------------------------
1 | #!/bin/zsh --no-rcs
2 |
3 | # Function to generate Alfred JSON output
4 | generate_output() {
5 | local items_array="$1"
6 | echo '{"items":['"$items_array"']}'
7 | }
8 |
9 | # Function to get Safari tabs
10 | get_safari_tabs() {
11 | osascript </g' \
63 | -e 's/%3[fF]/?/g' \
64 | -e 's/%40/@/g')
65 |
66 | # Replace non-alphanumeric characters with spaces (as in list-tabs-webkit.js)
67 | local clean_url=$(echo "$decoded_url" | sed -E 's/[^a-zA-Z0-9]/ /g')
68 |
69 | # Combine title and URL for the match
70 | echo "${title} ${clean_url}"
71 | }
72 |
73 | # Function to format tab items for Alfred JSON
74 | format_tab_items() {
75 | local tabs_list="$1"
76 | local items=""
77 | local first=true
78 |
79 | echo "$tabs_list" | while IFS= read -r line; do
80 | # Skip empty lines
81 | [[ -z "$line" ]] && continue
82 |
83 | # Extract window index, tab name, and URL
84 | local windowIndex=$(echo "$line" | cut -d' ' -f1)
85 | local tabName=$(echo "$line" | awk -F'"' '{print $2}')
86 | local tabURL=$(echo "$line" | awk -F'"' '{print $4}')
87 |
88 | # Create match string for Alfred filtering
89 | local match_string=$(create_match_string "$tabName" "$tabURL")
90 |
91 | # Escape JSON special characters
92 | tabName=$(echo "$tabName" | sed 's/\\/\\\\/g; s/"/\\"/g')
93 | tabURL=$(echo "$tabURL" | sed 's/\\/\\\\/g; s/"/\\"/g')
94 | match_string=$(echo "$match_string" | sed 's/\\/\\\\/g; s/"/\\"/g')
95 |
96 | # Add comma before item if not the first one
97 | if [ "$first" = true ]; then
98 | first=false
99 | else
100 | echo -n ","
101 | fi
102 |
103 | # Output item JSON with match property and quicklookurl like in list-tabs-webkit.js
104 | echo -n '{
105 | "uid": "'"$windowIndex"'",
106 | "title": "'"$tabName"'",
107 | "subtitle": "'"$tabURL"'",
108 | "arg": "'"$windowIndex,$tabURL"'",
109 | "icon": {"path": "./icon.png"},
110 | "match": "'"$match_string"'",
111 | "quicklookurl": "'"$tabURL"'"
112 | }'
113 | done
114 | }
115 |
116 | # Main function
117 | main() {
118 | # Check if Safari is running
119 | if ! pgrep -q "Safari"; then
120 | # Return error message
121 | generate_output '{"title":"Error","subtitle":"Safari is not running","valid":false}'
122 | return 0
123 | fi
124 |
125 | # Get all Safari windows and tabs
126 | local tabs_list=$(get_safari_tabs)
127 |
128 | # Process the output and format for Alfred
129 | if [[ -z "$tabs_list" ]]; then
130 | generate_output '{"title":"No tabs found","subtitle":"No open tabs in Safari","valid":false}'
131 | else
132 | local formatted_items=$(format_tab_items "$tabs_list")
133 | generate_output "$formatted_items"
134 | fi
135 | }
136 |
137 | # Run the main function
138 | main
139 |
--------------------------------------------------------------------------------
/src/new_private_window.zsh:
--------------------------------------------------------------------------------
1 | #!/bin/zsh --no-rcs
2 |
3 | # Function to validate URLs more rigorously but accept simple domains
4 | validate_url() {
5 | local input="$1"
6 | local url="$(echo "$input" | tr -d '\n\r' | xargs)"
7 |
8 | # If empty, return invalid
9 | if [[ -z "$url" ]]; then
10 | return 1
11 | fi
12 |
13 | # Check for spaces in the input (invalid for domains)
14 | if [[ "$url" =~ [[:space:]] ]]; then
15 | return 1
16 | fi
17 |
18 | # Add http:// if no protocol specified
19 | if [[ ! "$url" =~ ^https?:// ]]; then
20 | url="http://$url"
21 | fi
22 |
23 | # Extract domain (everything after protocol and before first slash or end)
24 | domain=$(echo "$url" | sed -E 's|^https?://([^/]+).*|\1|')
25 |
26 | # Basic domain validation: must contain at least one dot and some alphanumeric chars
27 | if [[ ! "$domain" =~ [[:alnum:]]+\.[[:alnum:]]+ ]]; then
28 | return 1
29 | fi
30 |
31 | # If we get here, URL seems valid
32 | echo "$url"
33 | return 0
34 | }
35 |
36 | # Initialize variables
37 | URL=""
38 | WINDOW_COUNT=1
39 |
40 | # Check if multiple windows are requested (x2, x3, etc.)
41 | if [[ $# -gt 0 && "$1" =~ ^x[0-9]+$ ]]; then
42 | # Extract number after 'x'
43 | WINDOW_COUNT=${1#x}
44 |
45 | # Validate it's a positive number
46 | if [[ ! "$WINDOW_COUNT" =~ ^[0-9]+$ || "$WINDOW_COUNT" -lt 1 ]]; then
47 | echo "Invalid window count: $WINDOW_COUNT. Using 1 instead." >&2
48 | WINDOW_COUNT=1
49 | elif [ "$WINDOW_COUNT" -gt 10 ]; then
50 | echo "Window count too high: $WINDOW_COUNT. Using 10 instead." >&2
51 | WINDOW_COUNT=10
52 | fi
53 |
54 | # Remove the window count parameter
55 | shift
56 | fi
57 |
58 | # Check if a URL was provided and validate it
59 | if [[ $# -gt 0 ]]; then
60 | input_url="$1"
61 | valid_url=$(validate_url "$input_url")
62 |
63 | if [[ $? -eq 0 ]]; then
64 | URL="$valid_url"
65 | else
66 | # URL is invalid, but continue without URL
67 | echo "Invalid URL format: '$input_url'. Opening Safari without URL." >&2
68 | fi
69 | fi
70 |
71 | # Get user language
72 | USER_LANG=$(defaults read -g AppleLocale | cut -d '_' -f 1)
73 |
74 | # Set menu items based on language
75 | if [[ "$USER_LANG" == "es" ]]; then
76 | NEW_PRIVATE_WINDOW="Nueva ventana privada"
77 | FILE_MENU="Archivo"
78 | else
79 | NEW_PRIVATE_WINDOW="New Private Window"
80 | FILE_MENU="File"
81 | fi
82 |
83 | # Check if Safari is running
84 | SAFARI_RUNNING=false
85 | if ps -e | grep -q "[S]afari$"; then
86 | SAFARI_RUNNING=true
87 | fi
88 |
89 | if ! $SAFARI_RUNNING; then
90 | # Safari is not running, start it
91 | open -a "Safari"
92 | # Wait for Safari to start
93 | sleep 1
94 |
95 | # Handle potential startup dialog
96 | osascript <&2
45 | return 1
46 | fi
47 |
48 | # Check if Safari is running
49 | local safari_running=false
50 | if ps -e | grep -q "[S]afari$"; then
51 | safari_running=true
52 | fi
53 |
54 | # If Safari is not running, start it
55 | if ! $safari_running; then
56 | open -a "Safari"
57 | sleep 0.5
58 | fi
59 |
60 | # Activate Safari and bring it to the foreground
61 | osascript -e 'tell application "Safari" to activate'
62 | sleep 0.2
63 |
64 | # Open the requested number of windows with the selected profile
65 | for ((i=1; i<=window_count; i++)); do
66 | # Use keyboard shortcut to switch to the selected profile
67 | # Option + Shift + Command + n where n is the profile number
68 | osascript <&2
110 | WINDOW_COUNT=1
111 | elif [ "$WINDOW_COUNT" -gt 10 ]; then
112 | echo "Window count too high: $WINDOW_COUNT. Using 10 instead." >&2
113 | WINDOW_COUNT=10
114 | fi
115 |
116 | # Remove the window count parameter
117 | shift
118 | fi
119 |
120 | # Check if a profile was requested (p1, p2, p3)
121 | if [[ $# -gt 0 && "$1" =~ ^p[1-3]$ ]]; then
122 | # Extract profile number
123 | PROFILE=${1#p}
124 | shift
125 | fi
126 |
127 | # Check if a URL was provided and validate it
128 | if [[ $# -gt 0 ]]; then
129 | input_url="$1"
130 | valid_url=$(validate_url "$input_url")
131 |
132 | if [[ $? -eq 0 ]]; then
133 | URL="$valid_url"
134 | else
135 | # URL is invalid, but continue without URL
136 | echo "Invalid URL format: '$input_url'. Opening Safari without URL." >&2
137 | fi
138 | fi
139 |
140 | # If a profile was specified, use that function
141 | if [[ -n "$PROFILE" ]]; then
142 | open_safari_with_profile "$PROFILE" "$URL" "$WINDOW_COUNT"
143 | exit $?
144 | fi
145 |
146 | # Otherwise, continue with the existing functionality
147 | SAFARI_IS_RUNNING=false
148 | if ps -e | grep -q "[S]afari$"; then
149 | SAFARI_IS_RUNNING=true
150 | fi
151 |
152 | # If Safari is not running, we need to handle it differently
153 | if ! $SAFARI_IS_RUNNING; then
154 | # Open Safari (which creates the first window)
155 | if [[ -n "$URL" ]]; then
156 | open -a "Safari" "$URL"
157 | else
158 | open -a "Safari"
159 | fi
160 |
161 | # Wait a moment for Safari to start
162 | sleep 0.5
163 |
164 | # Create additional windows (one less since Safari already opened one)
165 | if [[ $WINDOW_COUNT -gt 1 ]]; then
166 | for ((i=2; i<=WINDOW_COUNT; i++)); do
167 | if [[ -n "$URL" ]]; then
168 | osascript -e "tell application \"Safari\" to make new document with properties {URL:\"$URL\"}"
169 | else
170 | osascript -e 'tell application "Safari" to make new document'
171 | fi
172 | done
173 | fi
174 | else
175 | # Safari is already running, create the requested number of windows
176 | for ((i=1; i<=WINDOW_COUNT; i++)); do
177 | if [[ -n "$URL" ]]; then
178 | osascript -e "tell application \"Safari\" to make new document with properties {URL:\"$URL\"}"
179 | else
180 | osascript -e 'tell application "Safari" to make new document'
181 | fi
182 | done
183 | fi
184 |
185 | # Ensure Safari is in the foreground
186 | osascript -e 'tell application "Safari" to activate'
187 |
--------------------------------------------------------------------------------
/src/tab_to_private.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env osascript -l JavaScript
2 |
3 | function run() {
4 | try {
5 | // Check if Safari is running
6 | if (!Application("Safari").running()) {
7 | return JSON.stringify({
8 | items: [{
9 | title: "Error",
10 | subtitle: "Safari is not running",
11 | valid: false
12 | }]
13 | });
14 | }
15 |
16 | // Check if Safari is the frontmost application
17 | const frontmostApp = Application("System Events").applicationProcesses.whose({frontmost: true})[0].name();
18 |
19 | if (frontmostApp !== "Safari") {
20 | return JSON.stringify({
21 | items: [{
22 | title: "Error",
23 | subtitle: "Safari must be the active application",
24 | valid: false
25 | }]
26 | });
27 | }
28 |
29 | const safari = Application("Safari");
30 |
31 | // Check if there are any windows
32 | if (safari.windows.length === 0) {
33 | return JSON.stringify({
34 | items: [{
35 | title: "Error",
36 | subtitle: "There are no open windows in Safari",
37 | valid: false
38 | }]
39 | });
40 | }
41 |
42 | // Get the current tab's URL - use frontmost window
43 | const frontWindow = safari.windows.whose({ index: 1 })[0];
44 | const currentTab = frontWindow.currentTab;
45 |
46 | if (!currentTab || !currentTab.url() || currentTab.url() === "") {
47 | return JSON.stringify({
48 | items: [{
49 | title: "Error",
50 | subtitle: "The current tab has no URL (may be a new empty tab)",
51 | valid: false
52 | }]
53 | });
54 | }
55 |
56 | // For valid URLs, trim and return the URL directly without any whitespace
57 | return currentTab.url().trim();
58 |
59 | } catch (e) {
60 | return JSON.stringify({
61 | items: [{
62 | title: "Error",
63 | subtitle: "Error retrieving the URL from Safari: " + e.message,
64 | valid: false
65 | }]
66 | });
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/tab_to_private.zsh:
--------------------------------------------------------------------------------
1 | #!/bin/zsh --no-rcs
2 |
3 | # Check if Safari is running
4 | if ! pgrep -q "Safari"; then
5 | # Return JSON for Alfred with an error message
6 | echo '{"items":[{"title":"Error","subtitle":"Safari is not running","valid":false}]}'
7 | exit 1
8 | fi
9 |
10 | # Check if Safari is the active (frontmost) application
11 | ACTIVE_APP=$(osascript -e 'tell application "System Events" to name of first application process whose frontmost is true')
12 |
13 | if [[ "$ACTIVE_APP" != "Safari" ]]; then
14 | # Safari is running but not active
15 | echo '{"items":[{"title":"Error","subtitle":"Safari must be the active application","valid":false}]}'
16 | exit 1
17 | fi
18 |
19 | # Get the URL of the active tab using AppleScript
20 | CURRENT_URL=$(osascript <