forked from bit2pixel/chrome-control
-
Notifications
You must be signed in to change notification settings - Fork 1
/
chrome.js
executable file
·359 lines (305 loc) · 10.3 KB
/
chrome.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env osascript -l JavaScript
/**
* A JXA script and an Alfred Workflow for controlling Google Chrome (Javascript for Automation).
* Also see my "How I Navigate Hundreds of Tabs on Chrome with JXA and Alfred" article at [1]
* if you're interested in learning how I created the workflow.
* [1] https://medium.com/@bit2pixel/how-i-navigate-hundreds-of-tabs-on-chrome-with-jxa-and-alfred-9bbf971af02b
*/
ObjC.import('stdlib')
ObjC.import('Foundation')
const chrome = Application('Google Chrome')
chrome.includeStandardAdditions = true
// Mode flags
const MODE_CLI = 0 // Ask questions in command line
const MODE_UI = 1 // Ask questions with Chrome dialogs
const MODE_YES = 2 // Answer all questions with `yes`
let MODE = MODE_CLI // Default mode is command line
// Print the usage message
function usage() {
println('\n--------------')
println('Chrome Control')
println('--------------\n')
println('list List all open tabs in all Chrome windows usage: ./chrome.js list')
println('dedup Close duplicate tabs usage: ./chrome.js dedup')
println('close <winIdx,tabIdx> Close a specific tab in a specific window usage: ./chrome.js close 0,13')
println('close --title <string(s)> Close all tabs with titles containing strings usage: ./chrome.js close --title Inbox "iphone - apple"')
println('close --url <string(s)> Close all tabs with URLs containing strings usage: ./chrome.js close --url mail.google apple')
println('focus <winIdx,tabIdx> Focus on a specific tab in a specific window usage: ./chrome.js focus 0,13')
println('--ui If set, use Chrome to show messages usage ./chrome.js close --title inbox --ui')
println('--yes If set, all questions will be anwered with "y" usage ./chrome.js close --title inbox --yes')
$.exit(1)
}
// Run Chrome Control and catch all exceptions
function run(argv) {
try {
chromeControl(argv)
} catch (e) {
println(e)
}
}
// Chrome Control
function chromeControl(argv) {
if (argv.length < 1) { usage() }
// --ui flag will cause the questions to be asked using a
// Chrome dialog instead of text in command line.
let uiFlagIdx = argv.indexOf('--ui')
if (uiFlagIdx > -1) {
MODE = MODE_UI
argv.splice(uiFlagIdx, 1)
}
// --yes flag will cause no questions to be asked to the user.
// It'll close all tabs straight away so use it with caution.
let yesFlagIdx = argv.indexOf('--yes')
if (yesFlagIdx > -1) {
MODE = MODE_YES
argv.splice(yesFlagIdx, 1)
}
const cmd = argv[0]
if (cmd === 'list') {
list('all')
} else if (cmd === 'dedup') {
dedup()
} else if (cmd === 'close') {
if (argv.length == 1) { usage() }
if (argv.length == 2) {
const arg = argv[1]
closeTab(arg)
$.exit(0)
}
const subcmd = argv[1]
const keywords = argv.slice(2, argv.length)
closeByKeyword(subcmd, keywords)
} else if (cmd === 'focus') {
if (argv.length !== 2) { usage() }
const arg = argv[1]
focus(arg)
} else if (cmd === 'bookmarks') {
bookmarks()
} else if (cmd === 'open') {
open(argv[1])
} else {
usage()
}
$.exit(0)
}
/**
* Commands
*/
function parseUrlToKeywordsString(url) {
return url.split(/[\.\/\-_]/).filter(s => s && ! /https?:/.test(s)).join(' ')
}
// for more Chrome API refer https://medium.com/@bit2pixel/how-i-navigate-hundreds-of-tabs-on-chrome-with-jxa-and-alfred-9bbf971af02b
// for how to access the doc
function getAllBookmarks(folders, items) {
if (!folders) { return }
folders.forEach(folder => {
let folderName = folder.name()
getAllBookmarks(folder.bookmarkFolders(), items)
folder.bookmarkItems().forEach(bookmark => {
let title = bookmark.title()
let url = bookmark.url()
let key = `${folderName} ${title} ${parseUrlToKeywordsString(url)}`
items.push({
'folder': folderName,
'title': key,
'subtitle': url,
'arg': url,
})
})
})
}
// https://stevebarbera.medium.com/automating-chrome-with-jxa-javascript-application-scripting-6f9bc433216a
function open(url) {
// let firstWindow = chrome.windows
if (chrome.windows().length < 1) {
chrome.windows().make();
}
let activeWindow = chrome.windows()[0]
chrome.windows().forEach(w => {
if (w.visible === true) {
activeWindow = w
}
})
let newTab = new chrome.Tab()
newTab.url = url
activeWindow.tabs.push(newTab)
}
function bookmarks() {
let items = []
getAllBookmarks(chrome.bookmarkFolders(), items)
// can be viewed by
// ./chrome.js bookmarks | jq
out = { 'items': items }
// Print output
println(JSON.stringify(out))
}
// List all open tabs
function list() {
// Iterate all tabs in all windows
// Double entries arrays matching windows/tabs indexes (Using this improves a lot the performances)
let allTabsTitle = chrome.windows.tabs.title()
let allTabsUrls = chrome.windows.tabs.url()
var titleToUrl = {}
for (var winIdx = 0; winIdx < allTabsTitle.length; winIdx++) {
for (var tabIdx = 0; tabIdx < allTabsTitle[winIdx].length; tabIdx++) {
let title = allTabsTitle[winIdx][tabIdx]
let url = allTabsUrls[winIdx][tabIdx]
titleToUrl[title] = {
'title': `${title} ${parseUrlToKeywordsString(url)}`,
'url': url,
'winIdx': winIdx,
'tabIdx': tabIdx,
// Alfred specific properties
'arg': `${winIdx},${tabIdx}`,
'subtitle': url,
}
}
}
// Generate output
out = { 'items': [] }
Object.keys(titleToUrl).sort().forEach(title => {
out.items.push(titleToUrl[title])
})
// Print output
println(JSON.stringify(out))
}
// Close a specific tab
function closeTab(arg) {
let { winIdx, tabIdx } = parseWinTabIdx(arg)
let tabToClose = chrome.windows[winIdx].tabs[tabIdx]
// Ask the user before closing tab
areYouSure([tabToClose], 'Close this tab?', 'Couldn\'t find any matching tabs')
tabToClose.close()
}
// Close a tab if strings are found in the title or URL
function closeByKeyword(cmd, keywords) {
if (cmd === '--title') {
getProperty = function (tab) { return tab.title() }
}
else if (cmd === '--url') {
getProperty = function (tab) { return tab.url() }
} else {
usage()
}
let tabsToClose = []
// Iterate all tabs in all windows and compare the property returned
// by `getProperty` to the given keywords
chrome.windows().forEach(window => {
window.tabs().forEach(tab => {
keywords.forEach(keyword => {
if (getProperty(tab).toLowerCase().includes(keyword.toLowerCase())) {
tabsToClose.push(tab)
}
})
})
})
// Ask the user before closing tabs
areYouSure(tabsToClose, 'Close these tabs?', 'Couldn\'t find any matching tabs')
// Close tabs
tabsToClose.forEach(tab => { tab.close() })
}
// Focus on a specific tab
function focus(arg) {
let { winIdx, tabIdx } = parseWinTabIdx(arg)
chrome.windows[winIdx].visible = true
chrome.windows[winIdx].activeTabIndex = tabIdx + 1 // Focous on tab
chrome.windows[winIdx].index = 1 // Focus on this specific Chrome window
chrome.activate()
}
// Close duplicate tabs
function dedup() {
let urls = {}
let dups = []
chrome.windows().forEach(window => {
window.tabs().forEach(tab => {
const url = tab.url();
if (urls[url] === undefined) {
urls[url] = null
} else {
dups.push(tab)
}
})
})
// Ask the user before closing tabs
areYouSure(dups, 'Close these duplicates?', 'No duplicates found')
// Close tabs
dups.forEach(tab => { tab.close() })
}
/**
* Helpers
*/
// Show a message box in Chrome
const alert = function (msg) {
if (MODE === MODE_YES) {
return
}
chrome.activate()
chrome.displayAlert(msg)
}
// Grab input from the command line and return it
const prompt = function (msg) {
if (MODE === MODE_YES) {
return 'y'
} else if (MODE === MODE_UI) {
chrome.activate()
chrome.displayDialog(msg)
return
}
println(`\n${msg} (y/N)`)
return $.NSString.alloc.initWithDataEncoding(
$.NSFileHandle.fileHandleWithStandardInput.availableData,
$.NSUTF8StringEncoding
).js.trim()
}
// JXA always prints to stderr, so we need this custom print function
const print = function (msg) {
$.NSFileHandle.fileHandleWithStandardOutput.writeData(
$.NSString.alloc.initWithString(String(msg))
.dataUsingEncoding($.NSUTF8StringEncoding)
)
}
// Print with a new line at the end
const println = function (msg) {
print(msg + '\n')
}
// Ask the user before closing tabs
function areYouSure(tabsToClose, promptMsg, emptyMsg) {
// Give user feedback if no matching tabs were found
if (tabsToClose.length === 0) {
if (MODE == MODE_CLI) {
println(emptyMsg)
} else {
alert(emptyMsg)
}
$.exit(0)
}
// Grab the titles to show to the user
let titles = []
tabsToClose.forEach(tab => {
titles.push(tab.title())
})
// Focus on Chrome and ask user if they really want to close these tabs
if (MODE == MODE_CLI) {
println(`\n${titles.join('\n\n')}`)
if (prompt(promptMsg) !== 'y') {
println('Canceled')
$.exit(0)
}
} else {
prompt(`${promptMsg}\n\n${titles.join('\n\n')}`)
}
}
// Get winIdx and tabIdx from arg
function parseWinTabIdx(arg) {
const s = arg.split(',')
if (s.length !== 2) {
println('\nInvalid window and tab index. Example: 0,13\n')
usage()
}
let winIdx = parseInt(s[0])
let tabIdx = parseInt(s[1])
if (isNaN(winIdx) || isNaN(tabIdx)) {
throw ("Error: winIdx and tabIdx must be integers")
}
return { winIdx, tabIdx }
}