Repository navigation
Expand file tree
/
Copy pathredirector.user.js
More file actions
441 lines (414 loc) · 15.6 KB
/
Copy pathredirector.user.js
File metadata and controls
441 lines (414 loc) · 15.6 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// ==UserScript==
// @name Redirector
// @namespace shiftgeist
// @icon https://fav.farm/↗️
// @version 0.0.5
// @timestamp 20261105.094
//
// @match http://*/*
// @match https://*/*
// @grant GM_openInTab
// @grant window.close
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @run-at document-start
// @noframes
//
// @author shiftgeist
// @description Redirect pages with a configurable list of URLs.
// @license GNU GPLv3
//
// @homepage https://github.com/shiftgeist/userscripts
// @updateURL https://raw.githubusercontent.com/shiftgeist/userscripts/refs/heads/main/multi/redirector.user.js
// @downloadURL https://raw.githubusercontent.com/shiftgeist/userscripts/refs/heads/main/multi/redirector.user.js
// @supportURL https://github.com/shiftgeist/userscripts/issues
// ==/UserScript==
;(() => {
'use strict'
let timer
let countdown
let countdownHost
let countdownText
let deadline
let editor
let pauseTimer
let visibilityListener
const id = '[Redirector]'
const log = (...params) => {
try {
if (window.localStorage.getItem('debug') === 'true') console.debug(id, ...params)
} catch {}
}
const error = (...params) => console.error(id, ...params)
function stopTimer() {
pauseTimer?.()
pauseTimer = undefined
window.removeEventListener('visibilitychange', visibilityListener, true)
visibilityListener = undefined
window.clearTimeout(timer)
window.clearInterval(countdown)
deadline = undefined
hideCountdown()
}
function hideCountdown() {
window.clearInterval(countdown)
document.removeEventListener('mousemove', fadeCountdown)
countdownHost?.remove()
countdownHost = undefined
countdownText = undefined
}
function fadeCountdown(event) {
if (!countdownHost) return
const bounds = countdownHost.getBoundingClientRect()
const distance = Math.hypot(
Math.max(bounds.left - event.clientX, 0, event.clientX - bounds.right),
Math.max(bounds.top - event.clientY, 0, event.clientY - bounds.bottom)
)
countdownHost.style.opacity = distance <= 80 ? '0.1' : '1'
}
function updateCountdown() {
if (!document.body) return
if (!countdownHost) {
countdownHost = createElement('div')
countdownHost.style.cssText =
'all: initial; position: fixed; bottom: 16px; right: 16px; z-index: 2147483647; pointer-events: none; transition: opacity 150ms ease;'
const shadow = countdownHost.attachShadow({ mode: 'closed' })
countdownText = createElement('span')
shadow.append(createElement('style', {
textContent:
'span { display: block; padding: 8px 12px; border-radius: 8px; background: #202124; color: #fff; font: 14px/1.5 system-ui, sans-serif; font-variant-numeric: tabular-nums; }'
}), countdownText)
document.body.append(countdownHost)
document.addEventListener('mousemove', fadeCountdown)
}
const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000))
const minutes = Math.floor(seconds / 60)
countdownText.textContent = `Redirect in ${minutes}:${String(seconds % 60).padStart(2, '0')}`
}
function showCountdown() {
if (deadline === undefined) return
updateCountdown()
countdown = window.setInterval(updateCountdown, 1000)
}
function startCountdown(timestamp) {
deadline = timestamp
showCountdown()
}
function restoreDeadline(source, destination, delay, clearHistory) {
const rule = JSON.stringify([host(source), source.pathname, destination.href, delay,
clearHistory])
const timestamp = Date.now() + delay * 1000
try {
const saved = JSON.parse(window.sessionStorage.getItem('redirectorDeadline') ?? 'null')
if (saved?.rule === rule && Number.isFinite(saved.remaining)
&& saved.remaining >= 0 && saved.remaining <= delay * 1000)
{
return Date.now() + saved.remaining
}
if (saved?.rule === rule && Number.isFinite(saved.deadline)
&& saved.deadline <= timestamp) return saved.deadline
window.sessionStorage.setItem('redirectorDeadline',
JSON.stringify({ rule, deadline: timestamp }))
} catch (e) {
log('Could not restore the deadline:', e)
}
return timestamp
}
function saveTimer(remaining) {
try {
const saved = JSON.parse(window.sessionStorage.getItem('redirectorDeadline') ?? 'null')
if (!saved) return
saved.deadline = deadline
saved.remaining = deadline === undefined ? remaining : undefined
window.sessionStorage.setItem('redirectorDeadline', JSON.stringify(saved))
} catch (e) {
log('Could not save the timer:', e)
}
}
function clearSavedDeadline() {
try {
window.sessionStorage.removeItem('redirectorDeadline')
} catch (e) {
log('Could not clear the deadline:', e)
}
}
function validateRule(rule) {
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) {
throw new Error('Each redirect must be an object.')
}
const { from, to, delay = 0, clearHistory = false } = rule
if (typeof from !== 'string' || typeof to !== 'string') {
throw new Error('Each redirect needs from and to URLs.')
}
const source = parseAddress(from)
const destination = parseAddress(to)
if (![source, destination].every(url => ['http:', 'https:'].includes(url.protocol))) {
throw new Error('The URLs must use HTTP or HTTPS.')
}
if (!Number.isFinite(delay) || delay < 0 || delay * 1000 > 2147483647) {
throw new Error('The delay must be a non-negative number within the timer limit.')
}
if (typeof clearHistory !== 'boolean') {
throw new Error('The clearHistory option must be a boolean.')
}
return { source, destination, delay, clearHistory }
}
function parseAddress(value) {
const address = value.trim()
if (!address) throw new Error('Each redirect needs a source and destination address.')
const hasPort = /^[^/?#:\s]+:\d+(?:[/?#]|$)/.test(address)
const hasProtocol = !hasPort && /^[a-z][a-z\d+.-]*:/i.test(address)
return new URL(hasProtocol ? address : `https://${address}`)
}
function host(url) {
return url.host.replace(/^www\./, '')
}
function matches(source, current) {
return host(source) === host(current)
&& (source.pathname === '/' || source.pathname === current.pathname)
}
function addDefaults() {
if (GM_getValue('smallwebDefaultsAdded', false)) return
const redirects = GM_getValue('redirects', [])
if (!Array.isArray(redirects)) throw new Error('The stored list must be an array.')
for (const [domain, delay] of [['instagram.com', 600], ['youtube.com', 1200]]) {
const from = `https://${domain}/`
const exists = redirects.some(rule => {
try {
const { source } = validateRule(rule)
return host(source) === domain
} catch {
return false
}
})
if (!exists) {
redirects.push({ from, to: 'https://kagi.com/smallweb', delay, clearHistory: true })
}
}
GM_setValue('redirects', redirects)
GM_setValue('smallwebDefaultsAdded', true)
}
function createElement(tag, properties = {}, children = []) {
const element = document.createElement(tag)
Object.assign(element, properties)
element.append(...children)
return element
}
function editRedirects() {
if (editor) {
editor.focus()
return
}
if (!document.body) {
document.addEventListener('DOMContentLoaded', editRedirects, { once: true })
return
}
stopTimer()
const host = createElement('div')
const shadow = host.attachShadow({ mode: 'closed' })
const style = createElement('style', {
textContent: `
:host { all: initial; }
* { box-sizing: border-box; }
dialog { width: min(960px, calc(100vw - 32px)); max-height: calc(100vh - 32px);
padding: 24px; border: 1px solid #bbb; border-radius: 12px;
background: #fff; color: #202124; font: 15px/1.5 system-ui, sans-serif; }
dialog::backdrop { background: #0008; }
h2 { margin: 0 0 12px; }
p { margin: 0 0 16px; }
fieldset { display: grid; grid-template-columns: 1fr 1fr; gap: 12px;
margin: 0 0 16px; padding: 16px; border: 1px solid #ccc; border-radius: 8px; }
label { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
label.checkbox { flex-direction: row; align-items: center; }
input, select { width: 100%; padding: 8px; border: 1px solid #888; border-radius: 4px;
background: #fff; color: #202124; font: inherit; }
input[type=checkbox] { width: auto; }
button { padding: 8px 14px; border: 1px solid #888; border-radius: 4px;
background: #f3f4f6; color: #202124; cursor: pointer; font: inherit; }
button[type=submit] { background: #185abc; border-color: #185abc; color: #fff; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; }
.actions > :first-child { margin-right: auto; }
.error { color: #b3261e; white-space: pre-wrap; }
@media (max-width: 640px) { fieldset { grid-template-columns: 1fr; } }
`
})
const title = createElement('h2', { id: 'redirector-title', textContent: 'Redirects' })
const help = createElement('p', {
textContent:
'The first matching rule applies. The host and port must match. A source path matches only that path. A bare domain matches all paths. Rules ignore the protocol and www. Addresses do not need https://. Changes apply on the next page visit. “Close old tab” does not delete your browser history.'
})
const rows = createElement('div')
const message = createElement('p', { className: 'error' })
message.setAttribute('role', 'alert')
const fields = []
const form = document.createElement('form')
const dialog = document.createElement('dialog')
dialog.setAttribute('aria-labelledby', title.id)
let saved = false
function addRow(rule = {}) {
const from = createElement('input', { type: 'text', required: true, value: rule.from ?? '' })
const to = createElement('input', { type: 'text', required: true, value: rule.to ?? '' })
const delay = createElement('input', {
type: 'number',
min: '0',
max: '2147483.647',
step: 'any',
required: true,
value: String(rule.delay ?? 0)
})
const clearHistory = createElement('input', { type: 'checkbox',
checked: rule.clearHistory === true })
const remove = createElement('button', { type: 'button', textContent: 'Delete' })
const row = createElement('fieldset', {}, [
createElement('legend', { textContent: 'Redirect' }),
createElement('label', {}, ['Source address', from]),
createElement('label', {}, ['Destination address', to]),
createElement('label', {}, ['Delay in seconds', delay]),
createElement('label', { className: 'checkbox' }, [clearHistory, 'Close old tab']),
remove
])
const entry = { row, from, to, delay, clearHistory }
fields.push(entry)
remove.addEventListener('click', () => {
fields.splice(fields.indexOf(entry), 1)
row.remove()
})
rows.append(row)
return from
}
const add = createElement('button', { type: 'button', textContent: 'Add' })
const cancel = createElement('button', { type: 'button', textContent: 'Cancel' })
const save = createElement('button', { type: 'submit', textContent: 'Save' })
add.addEventListener('click', () => addRow({ from: window.location.href }).focus())
cancel.addEventListener('click', () => dialog.close())
form.addEventListener('submit', event => {
event.preventDefault()
message.textContent = ''
try {
const redirects = fields.map(({ from, to, delay, clearHistory }, index) => {
const rule = {
from: from.value.trim(),
to: to.value.trim(),
delay: Number(delay.value),
clearHistory: clearHistory.checked
}
try {
validateRule(rule)
} catch (e) {
throw new Error(`Redirect ${index + 1}: ${e.message}`)
}
return rule
})
GM_setValue('redirects', redirects)
saved = true
dialog.close()
} catch (e) {
error(e)
message.textContent = `Could not save: ${e.message}`
}
})
dialog.addEventListener('close', () => {
host.remove()
editor = undefined
if (!saved) {
try {
main()
} catch (e) {
error(e)
}
}
}, { once: true })
try {
const redirects = GM_getValue('redirects', [])
if (!Array.isArray(redirects)) throw new Error('The stored list must be an array.')
redirects.forEach(rule => addRow(rule ?? {}))
} catch (e) {
error(e)
message.textContent = `Could not open the complete list: ${e.message}`
}
form.append(title, help, rows, message,
createElement('div', { className: 'actions' }, [add, cancel, save]))
dialog.append(form)
shadow.append(style, dialog)
document.body.append(host)
editor = dialog
dialog.showModal()
}
function redirect(source, destination, clearHistory) {
const current = new URL(window.location.href)
if (!matches(source, current)) return
if (destination.href === current.href) return
try {
log('Redirect:', current.href, destination.href)
if (clearHistory) {
const tab = GM_openInTab(destination.href, { active: true })
if (!tab) throw new Error('Could not open the destination tab.')
window.close()
} else {
window.location.replace(destination.href)
}
} catch (e) {
error(e)
}
}
function main() {
const redirects = GM_getValue('redirects', [])
if (!Array.isArray(redirects)) throw new Error('The stored list must be an array.')
for (const rule of redirects) {
try {
const { source, destination, delay, clearHistory } = validateRule(rule)
const current = new URL(window.location.href)
if (!matches(source, current)) continue
if (destination.href === window.location.href) return
let remaining = Math.max(0,
restoreDeadline(source, destination, delay, clearHistory) - Date.now())
const finish = () => {
stopTimer()
clearSavedDeadline()
redirect(source, destination, clearHistory)
}
pauseTimer = () => {
if (deadline !== undefined) remaining = Math.max(0, deadline - Date.now())
window.clearTimeout(timer)
deadline = undefined
hideCountdown()
saveTimer(remaining)
}
visibilityListener = () => {
if (document.visibilityState !== 'visible') {
pauseTimer()
return
}
if (deadline !== undefined) return
if (remaining === 0) {
finish()
return
}
startCountdown(Date.now() + remaining)
saveTimer(remaining)
timer = window.setTimeout(() => {
if (document.visibilityState !== 'visible') {
pauseTimer()
return
}
finish()
}, remaining)
}
window.addEventListener('visibilitychange', visibilityListener, true)
window.addEventListener('pagehide', stopTimer, { once: true })
visibilityListener()
return
} catch (e) {
error(e)
}
}
}
try {
addDefaults()
GM_registerMenuCommand('Edit redirects', editRedirects)
main()
} catch (e) {
error(e)
}
})()