-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGitHub_Tab_Avatar.user.js
More file actions
217 lines (194 loc) · 6.69 KB
/
GitHub_Tab_Avatar.user.js
File metadata and controls
217 lines (194 loc) · 6.69 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
// ==UserScript==
// @name GitHub Tab Avatar
// @namespace https://github.com/sinazadeh/userscripts
// @version 1.0.2
// @description Use each GitHub repository’s avatar as the browser tab icon.
// @author TheSina
// @match *://github.com/*/*
// @grant none
// @license MIT
// @downloadURL https://raw.githubusercontent.com/sinazadeh/userscripts/refs/heads/main/GitHub_Tab_Avatar.user.js
// @updateURL https://raw.githubusercontent.com/sinazadeh/userscripts/refs/heads/main/GitHub_Tab_Avatar.meta.js
// ==/UserScript==
/* jshint esversion: 11 */
(function () {
'use strict';
const CACHE_TTL = 24 * 3600 * 1000;
const STORAGE_KEY = 'githubTabAvatarCache';
const DEBUG = false;
const LOG = (...args) => DEBUG && console.log('[GTU]', ...args);
let iconEls = [];
let originalIcon = null;
let lastOwner = null;
// load cache from localStorage
let iconCache = new Map();
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
JSON.parse(raw).forEach(([owner, entry]) => {
if (Date.now() - entry.ts < CACHE_TTL) {
iconCache.set(owner, entry);
}
});
}
} catch {}
let isUpdating = false;
function getOwnerName() {
const pathSegments = location.pathname.split('/').filter(s => s);
// We need at least two segments to determine the owner
if (pathSegments.length < 2) return null;
const [segment1, segment2] = pathSegments;
// If the first segment is 'orgs', the owner is the second segment
if (segment1 === 'orgs') {
return segment2;
}
// If the first segment is a known non-target, or just a user page, return null
const nonTargetSegments = new Set([
'settings',
'notifications',
'pulls',
'issues',
'marketplace',
'explore',
'organizations',
'account',
]);
if (nonTargetSegments.has(segment1)) {
return null;
}
// Otherwise, the owner is the first segment
return segment1;
}
function setFavicon(url) {
if (!iconEls.length || !document.contains(iconEls[0])) {
initFaviconTags();
}
iconEls.forEach(el => {
if (el && document.contains(el)) {
el.href = url;
}
});
}
function resetFavicon() {
if (originalIcon) setFavicon(originalIcon);
}
function initFaviconTags() {
if (!iconEls.length || !document.contains(iconEls[0])) {
iconEls = Array.from(
document.querySelectorAll('link[rel*="icon"]'),
);
if (!iconEls.length) {
const link = document.createElement('link');
link.rel = 'shortcut icon';
document.head.appendChild(link);
iconEls = [link];
}
if (!originalIcon && iconEls[0]) {
originalIcon =
iconEls[0].href || 'https://github.com/favicon.ico';
}
}
}
// try DOM first (new method)
async function getAvatarFromAPI(owner) {
try {
LOG('🚀 Using GitHub API to find avatar for:', owner);
const res = await fetch(`https://api.github.com/users/${owner}`, {
headers: {Accept: 'application/vnd.github.v3+json'},
});
if (!res.ok) throw new Error('API response not OK');
const data = await res.json();
if (data?.avatar_url) {
const urlObj = new URL(data.avatar_url);
urlObj.searchParams.set('s', '32');
return urlObj.href;
}
} catch (err) {
LOG('⚠️ API lookup failed:', err);
}
return null;
}
async function updateFavicon() {
if (isUpdating) return;
isUpdating = true;
try {
const owner = getOwnerName();
if (!owner) {
resetFavicon();
lastOwner = null;
return;
}
// cached?
if (owner === lastOwner && iconCache.has(owner)) {
const cached = iconCache.get(owner);
if (Date.now() - cached.ts < CACHE_TTL) {
setFavicon(cached.url);
return;
}
}
lastOwner = owner;
const avatarUrl = await getAvatarFromAPI(owner);
if (avatarUrl) {
iconCache.set(owner, {url: avatarUrl, ts: Date.now()});
try {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify([...iconCache]),
);
} catch {}
setFavicon(avatarUrl);
LOG('✅ Favicon updated successfully');
} else {
LOG('⚠️ No avatar found, using default');
resetFavicon();
}
} finally {
isUpdating = false;
}
}
function debounce(fn, ms) {
let t;
return function (...args) {
clearTimeout(t);
t = setTimeout(() => fn.apply(this, args), ms);
};
}
const debouncedUpdate = debounce(updateFavicon, 300);
function handleNavigation() {
LOG('🧭 Navigation detected');
lastOwner = null; // Invalidate cache on navigation
debouncedUpdate();
}
function start() {
LOG('🚀 Starting GitHub Tab Avatar');
initFaviconTags();
debouncedUpdate();
document.addEventListener('turbo:load', handleNavigation);
document.addEventListener('turbo:render', () =>
setTimeout(handleNavigation, 200),
);
const originalPushState = history.pushState;
history.pushState = function (...args) {
originalPushState.apply(history, args);
handleNavigation();
};
const originalReplaceState = history.replaceState;
history.replaceState = function (...args) {
originalReplaceState.apply(history, args);
handleNavigation();
};
window.addEventListener('popstate', handleNavigation);
setInterval(() => {
const currentOwner = getOwnerName();
if (currentOwner && currentOwner !== lastOwner) {
LOG('🔄 Polling detected change');
handleNavigation();
}
}, 1000);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();