1#!/usr/bin/env osascript -l JavaScript
2// A script to close Safari tabs.
4// This is a script I run when I see high memory usage in Activity Monitor --
5// it shows me the URL but no easy way to jump to the tab. If I recognise
6// the URL and I know I can close it safely, this script lets me do that
9safari = Application("Safari");
11// Generates all the window/tab/URLs in Safari.
13// This runs in reverse window/tab index order: that is, windows are returned
14// bottom to top, and tabs from right to left.
15function* tabGenerator() {
16 window_count = safari.windows.length;
18 for (window_index = window_count - 1; window_index >= 0; window_index--) {
19 window = safari.windows[window_index];
21 tab_count = window.tabs.length;
23 for (tab_index = tab_count - 1; tab_index >= 0; tab_index--) {
24 tab = window.tabs[tab_index];
26 if (tab.url() !== null) {
27 yield [window_index, tab_index, tab.url(), tab.name()];
36 let remainingCount = 0;
38 for (const [window_index, tab_index, url, title] of tabGenerator()) {
39 for (i = 0; i < argv.length; i++) {
40 const searchFragment = argv[i];
42 if (url.includes(searchFragment)) {
43 console.log(`${url} (${title})`);
44 safari.windows[window_index].tabs[tab_index].close();
53 console.log(`Closed ${closedCount} tab${closedCount !== 1 ? 's' : ''}; ${remainingCount} tab${remainingCount !== 1 ? 's' : ''} left open`)