-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
327 lines (282 loc) · 12 KB
/
content.js
File metadata and controls
327 lines (282 loc) · 12 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
// YouTube → Claude Transcriber — Content Script (ISOLATED world)
// Handles UI + communicates with MAIN world page script for transcript extraction
const ICON_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="16" y1="13" x2="8" y2="13"/>
<line x1="16" y1="17" x2="8" y2="17"/>
<polyline points="10 9 9 9 8 9"/>
</svg>`;
// ─── Page script communication ───
let requestCounter = 0;
const pendingRequests = new Map();
function requestFromPage(videoId) {
return new Promise((resolve, reject) => {
const requestId = 'ytc-' + (++requestCounter);
const timeout = setTimeout(() => {
pendingRequests.delete(requestId);
reject(new Error('Page script timeout (15s)'));
}, 15000);
pendingRequests.set(requestId, { resolve, reject, timeout });
window.dispatchEvent(new CustomEvent('ytc-request', {
detail: {
videoId,
requestId,
preferLang: settings.ytcDefaultLang || 'auto',
includeTimestamps: settings.ytcIncludeTimestamps
}
}));
});
}
window.addEventListener('ytc-response', (e) => {
const { requestId, ...data } = e.detail;
const pending = pendingRequests.get(requestId);
if (!pending) return;
pendingRequests.delete(requestId);
clearTimeout(pending.timeout);
pending.resolve(data);
});
// ─── Video Info ───
function getVideoId() {
return new URLSearchParams(window.location.search).get('v');
}
function getVideoTitle() {
const selectors = [
'h1.ytd-watch-metadata yt-formatted-string',
'h1.style-scope.ytd-watch-metadata',
'#title h1 yt-formatted-string',
'h1.title',
];
for (const sel of selectors) {
const el = document.querySelector(sel);
if (el?.textContent?.trim()) return el.textContent.trim();
}
return document.title.replace(' - YouTube', '').trim();
}
// ─── Toast ───
function showToast(message, type = '') {
let toast = document.querySelector('.ytc-toast');
if (!toast) {
toast = document.createElement('div');
toast.className = 'ytc-toast';
document.body.appendChild(toast);
}
toast.textContent = message;
toast.className = `ytc-toast ${type ? `ytc-${type}` : ''}`;
requestAnimationFrame(() => toast.classList.add('ytc-visible'));
clearTimeout(toast._timeout);
toast._timeout = setTimeout(() => toast.classList.remove('ytc-visible'), 4000);
}
// ─── Core Action ───
async function transcribeAndSend(videoId = null) {
const isWidget = !videoId;
const vid = videoId || getVideoId();
if (!vid) {
const msg = 'No video ID found. Navigate to a YouTube video first.';
isWidget ? setWidgetStatus(msg, 'error') : showToast(msg, 'error');
return;
}
const statusFn = isWidget
? (msg, type) => setWidgetStatus(msg, type)
: (msg, type) => showToast(msg, type);
try {
statusFn('Extracting transcript...', 'loading');
// Ask page script to get transcript (it runs in MAIN world with page context)
const result = await requestFromPage(vid);
if (!result.success) {
throw new Error(result.error || 'Failed to extract transcript');
}
const transcript = result.transcript;
if (!transcript || transcript.trim().length === 0) {
throw new Error('Empty transcript returned');
}
const title = getVideoTitle();
const url = `https://www.youtube.com/watch?v=${vid}`;
lastTranscript = transcript;
lastTitle = title;
lastUrl = url;
const prompt = await buildPrompt(title, transcript, url);
statusFn('Opening Claude...', 'success');
chrome.runtime.sendMessage({ action: 'openClaude', prompt });
if (isWidget) setTimeout(() => setWidgetStatus(''), 3000);
} catch (err) {
console.error('[YTC] Failed:', err);
statusFn(err.message || 'Failed', 'error');
if (isWidget) setTimeout(() => setWidgetStatus(''), 6000);
}
}
const DEFAULT_MAIN_PROMPT = `Create an artefact so I can export this in markdown. You are an expert, genius transcriber, and your objective is to provide the most accurate representation of the transcript I provide you, in bullet point form, capturing all key information and details without omitting or paraphrasing any part of the content. You are provided the title and transcript of a Youtube video in triple quotes. Reproduce this YouTube video transcript in text format for the deaf reader. I need the entire content summarised to capture the knowledge without watching the video. Format your output so each "section" of the video is represented. within each section are the bullet points that fully explain the section. DO NOT use terms that would represent the person in the video talking about a topic: eg "PERSON A talks about their experiences." INSTEAD use: "PERSON A talks about their experiences [here will be those experiences, explained]." If your message output stops before completing the entire transcript contents, you must finish the message letting me know and prompting me to continue the task. Finally, Rename this chat to match the video Title I give you. Use plain markdown formatting, and use hyphens and bullet points. Here's the transcript:
Title: "\${title}"
Transcript: "\${transcript}"
URL: "\${url}"`;
async function buildPrompt(title, transcript, url) {
const data = await chrome.storage.local.get('ytcMainPrompt');
const template = data.ytcMainPrompt || DEFAULT_MAIN_PROMPT;
return template
.replace(/\$\{title\}/g, title)
.replace(/\$\{transcript\}/g, transcript)
.replace(/\$\{url\}/g, url);
}
// ─── Copy helpers ───
let lastTranscript = '';
let lastTitle = '';
let lastUrl = '';
const COPY_SVG = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`;
async function fetchTranscriptOnly() {
const vid = getVideoId();
if (!vid) return;
setWidgetStatus('Extracting...', 'loading');
try {
const result = await requestFromPage(vid);
if (!result.success) throw new Error(result.error || 'Failed');
lastTranscript = result.transcript;
lastTitle = getVideoTitle();
lastUrl = `https://www.youtube.com/watch?v=${vid}`;
} catch (err) {
setWidgetStatus(err.message, 'error');
setTimeout(() => setWidgetStatus(''), 4000);
throw err;
}
}
async function copyTranscriptOnly() {
try {
if (!lastTranscript) await fetchTranscriptOnly();
await navigator.clipboard.writeText(lastTranscript);
setWidgetStatus('✓ Transcript copied!', 'success');
setTimeout(() => setWidgetStatus(''), 3000);
} catch (err) {
setWidgetStatus(err.message || 'Failed', 'error');
setTimeout(() => setWidgetStatus(''), 4000);
}
}
async function copyWithPrompt() {
try {
if (!lastTranscript) await fetchTranscriptOnly();
const prompt = await buildPrompt(lastTitle, lastTranscript, lastUrl);
await navigator.clipboard.writeText(prompt);
setWidgetStatus('✓ Prompt + transcript copied!', 'success');
setTimeout(() => setWidgetStatus(''), 3000);
} catch (err) {
setWidgetStatus(err.message || 'Failed', 'error');
setTimeout(() => setWidgetStatus(''), 4000);
}
}
// ─── Settings cache ───
let settings = {
ytcWidgetVisible: true,
ytcWidgetPosition: 'below-title',
ytcIncludeTimestamps: false,
ytcDefaultLang: 'auto',
ytcAutoSend: true,
};
function loadSettings() {
return chrome.storage.local.get([
'ytcWidgetVisible', 'ytcWidgetPosition', 'ytcIncludeTimestamps',
'ytcDefaultLang', 'ytcAutoSend'
]).then(data => {
settings.ytcWidgetVisible = data.ytcWidgetVisible !== false;
settings.ytcWidgetPosition = data.ytcWidgetPosition || 'below-title';
settings.ytcIncludeTimestamps = data.ytcIncludeTimestamps === true;
settings.ytcDefaultLang = data.ytcDefaultLang || 'auto';
settings.ytcAutoSend = data.ytcAutoSend !== false;
});
}
// Reload settings when changed from options page
chrome.storage.onChanged.addListener((changes) => {
for (const key of Object.keys(changes)) {
if (key in settings) settings[key] = changes[key].newValue;
}
// Re-apply widget visibility/position
if (changes.ytcWidgetVisible || changes.ytcWidgetPosition) {
document.querySelector('.ytc-widget')?.remove();
widgetEl = null;
if (window.location.pathname === '/watch') createWidget();
}
});
// ─── Widget ───
let widgetEl = null;
function setWidgetStatus(text, type = '') {
const status = widgetEl?.querySelector('.ytc-status');
if (!status) return;
status.textContent = text;
status.className = `ytc-status ${type ? `ytc-${type}` : ''}`;
}
function createWidget() {
if (!settings.ytcWidgetVisible) return;
if (document.querySelector('.ytc-widget')) return;
widgetEl = document.createElement('div');
widgetEl.className = 'ytc-widget';
if (settings.ytcWidgetPosition === 'floating') widgetEl.classList.add('ytc-floating');
widgetEl.innerHTML = `
<button class="ytc-btn" data-action="transcribe">${ICON_SVG}<span>Transcribe → Claude</span></button>
<button class="ytc-btn ytc-btn-secondary" data-action="copy-transcript">${COPY_SVG}<span>Copy Transcript</span></button>
<button class="ytc-btn ytc-btn-secondary" data-action="copy-prompt">${COPY_SVG}<span>Copy with Prompt</span></button>
<span class="ytc-status"></span>
`;
widgetEl.querySelector('[data-action="transcribe"]').addEventListener('click', () => transcribeAndSend());
widgetEl.querySelector('[data-action="copy-transcript"]').addEventListener('click', () => copyTranscriptOnly());
widgetEl.querySelector('[data-action="copy-prompt"]').addEventListener('click', () => copyWithPrompt());
if (settings.ytcWidgetPosition === 'floating') {
document.body.appendChild(widgetEl);
} else {
const targets = ['#above-the-fold #top-row', '#above-the-fold', '#info-contents', 'ytd-watch-metadata'];
const tryInsert = () => {
for (const sel of targets) {
const t = document.querySelector(sel);
if (t) { t.insertAdjacentElement('afterend', widgetEl); return true; }
}
return false;
};
if (!tryInsert()) {
const obs = new MutationObserver(() => { if (tryInsert()) obs.disconnect(); });
obs.observe(document.body, { childList: true, subtree: true });
setTimeout(() => obs.disconnect(), 15000);
}
}
}
// ─── Thumbnails ───
function addThumbnailButtons() {
document.querySelectorAll('ytd-thumbnail:not([data-ytc])').forEach(thumb => {
thumb.setAttribute('data-ytc', '1');
const link = thumb.querySelector('a#thumbnail, a.yt-simple-endpoint');
if (!link) return;
const href = link.getAttribute('href');
if (!href) return;
const match = href.match(/\/watch\?v=([^&]+)/) || href.match(/\/shorts\/([^?&]+)/);
if (!match) return;
const btn = document.createElement('div');
btn.className = 'ytc-thumb-btn';
btn.innerHTML = ICON_SVG;
btn.title = 'Transcribe with Claude';
btn.addEventListener('click', (e) => {
e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation();
transcribeAndSend(match[1]);
}, true);
thumb.appendChild(btn);
});
}
// ─── Init ───
function init() {
if (window.location.pathname === '/watch') createWidget();
addThumbnailButtons();
}
// Listen for keyboard shortcut trigger from background
chrome.runtime.onMessage.addListener((msg) => {
if (msg.action === 'triggerTranscribe') transcribeAndSend();
});
let lastNavUrl = location.href;
new MutationObserver(() => {
if (location.href !== lastNavUrl) {
lastNavUrl = location.href;
document.querySelector('.ytc-widget')?.remove();
widgetEl = null;
lastTranscript = '';
lastTitle = '';
lastUrl = '';
setTimeout(init, 800);
}
addThumbnailButtons();
}).observe(document.body, { childList: true, subtree: true });
loadSettings().then(() => {
document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', init) : init();
});