Files
background.js
content.css
content.js
manifest.json
popup.html
popup.js
Code
6 564
background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'download_video') {
handleDownload(message, sendResponse);
return true;
}
});
async function handleDownload(msg, sendResponse) {
const videoId = msg.videoId;
const format = msg.format || 'mp4';
const allowedFormats = ['mp3', 'mp3-hd', 'm4a', 'mp4', 'mp4-hd', 'mp4-2k', 'wav', '3gp', 'flv'];
let tabId;
let downloadWait;
try {
if (typeof videoId !== 'string' || !/^[A-Za-z0-9_-]{11}$/.test(videoId)) {
throw new Error('Invalid YouTube video ID');
}
if (!allowedFormats.includes(format)) {
throw new Error('Unsupported download format');
}
const notubeUrl = 'https://notube.cc/';
const tab = await chrome.tabs.create({ url: notubeUrl, active: false });
if (typeof tab.id !== 'number') throw new Error('Could not open the download page');
tabId = tab.id;
await waitForTabComplete(tabId, 30000);
await new Promise(resolve => setTimeout(resolve, 1500));
downloadWait = createDownloadWait(tabId, videoId, 120000);
const results = await chrome.scripting.executeScript({
target: { tabId },
func: triggerNotubeDownload,
args: [`https://www.youtube.com/watch?v=${videoId}`, format]
});
const triggerResult = results?.[0]?.result;
if (typeof triggerResult !== 'string' || triggerResult.startsWith('no format option found')) {
throw new Error(triggerResult || 'Could not select the requested format');
}
const download = await downloadWait.promise;
if (!download) throw new Error('Download was cancelled');
downloadWait = null;
sendResponse({ success: true });
} catch (err) {
console.error('Download failed:', err);
sendResponse({ success: false, error: err.message || 'Download failed' });
} finally {
if (downloadWait) downloadWait.cancel();
if (typeof tabId === 'number') {
try {
await chrome.tabs.remove(tabId);
} catch (error) {
console.error('Failed to close download tab:', error);
}
}
}
}
function waitForTabComplete(tabId, timeoutMs) {
return new Promise((resolve, reject) => {
let settled = false;
let timeoutId;
const cleanup = () => {
clearTimeout(timeoutId);
chrome.tabs.onUpdated.removeListener(listener);
};
const finish = error => {
if (settled) return;
settled = true;
cleanup();
if (error) reject(error);
else resolve();
};
const listener = (updatedTabId, changeInfo) => {
if (updatedTabId === tabId && changeInfo.status === 'complete') finish();
};
chrome.tabs.onUpdated.addListener(listener);
timeoutId = setTimeout(() => finish(new Error('Download page load timed out')), timeoutMs);
chrome.tabs.get(tabId).then(tab => {
if (tab.status === 'complete') finish();
}).catch(finish);
});
}
function createDownloadWait(tabId, videoId, timeoutMs) {
let resolvePromise;
let rejectPromise;
let timeoutId;
let settled = false;
const promise = new Promise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
const cleanup = () => {
clearTimeout(timeoutId);
chrome.downloads.onCreated.removeListener(listener);
};
const listener = item => {
let matchingReferrer = false;
if (item.referrer) {
try {
const referrer = new URL(item.referrer);
matchingReferrer = referrer.protocol === 'https:' && referrer.hostname === 'notube.cc' && referrer.searchParams.get('v') === videoId;
} catch (error) {
console.error('Failed to parse download referrer:', error);
}
}
if (item.tabId !== tabId && !matchingReferrer) return;
settled = true;
cleanup();
resolvePromise(item);
};
chrome.downloads.onCreated.addListener(listener);
timeoutId = setTimeout(() => {
if (settled) return;
settled = true;
cleanup();
rejectPromise(new Error('No download started within the timeout'));
}, timeoutMs);
return {
promise,
cancel() {
if (settled) return;
settled = true;
cleanup();
resolvePromise(null);
}
};
}
function triggerNotubeDownload(videoUrl, format) {
const formatLabels = {
'mp3': ['mp3'],
'mp3-hd': ['mp3hd'],
'm4a': ['m4a'],
'mp4': ['mp4'],
'mp4-hd': ['mp4hd'],
'mp4-2k': ['mp42k', '2k'],
'wav': ['wav'],
'3gp': ['3gp'],
'flv': ['flv']
};
const labels = formatLabels[format];
if (!labels) return 'unsupported format: ' + format;
const normalize = value => (value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
const isVisible = el => {
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 && getComputedStyle(el).visibility !== 'hidden';
};
const inputs = Array.from(document.querySelectorAll('input[type="url"], input[type="text"], input[type="search"], textarea'))
.filter(isVisible)
.map(el => {
const hint = [el.name, el.id, el.placeholder, el.getAttribute('aria-label')].join(' ').toLowerCase();
const score = /url|video|youtube|link/.test(hint) ? 1 : 0;
return { el, score };
})
.sort((a, b) => b.score - a.score);
const input = inputs[0]?.el;
const form = input?.form || input?.closest('form');
if (!input || !form) return 'could not find the converter form';
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');
if (descriptor?.set) descriptor.set.call(input, videoUrl);
else input.value = videoUrl;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
const select = Array.from(form.querySelectorAll('select')).find(isVisible);
if (select) {
const option = Array.from(select.options).find(option => labels.includes(normalize(option.value)) || labels.includes(normalize(option.textContent)));
if (!option) return 'requested format is not available on the converter page';
select.value = option.value;
select.dispatchEvent(new Event('input', { bubbles: true }));
select.dispatchEvent(new Event('change', { bubbles: true }));
}
const submit = form.querySelector('button[type="submit"], input[type="submit"], button:not([type])');
if (submit && isVisible(submit)) submit.click();
else if (typeof form.requestSubmit === 'function') form.requestSubmit();
else return 'could not submit the converter form';
return 'converter form submitted';
}