');
const tpl = document.createElement('template');
tpl.innerHTML = decoded;
tpl.content.querySelectorAll('script, style, iframe, form, button').forEach(el => el.remove());
return tpl.innerHTML;
};
const getOfficialSub = () => {
const descEl = document.querySelector(DESC_SELECTOR);
const match = descEl?.textContent?.match(/reddit\.com\/r\/([^ /\n\r?]+)/i);
return match ? match[1].toLowerCase() : null;
};
const getMount = () => {
let mount = document.getElementById(MOUNT_ID);
if (mount && mount.isConnected) return mount;
const comments = document.querySelector('#comments, ytd-comments');
if (comments && comments.parentNode) {
mount = document.createElement('div');
mount.id = MOUNT_ID;
comments.parentNode.insertBefore(mount, comments);
return mount;
}
const meta = document.querySelector('#below > ytd-watch-metadata, #below > #watch-metadata');
if (meta && meta.parentNode) {
mount = document.createElement('div');
mount.id = MOUNT_ID;
meta.parentNode.insertBefore(mount, meta.nextSibling);
return mount;
}
const below = document.querySelector('#below');
if (below) {
mount = document.createElement('div');
mount.id = MOUNT_ID;
below.append(mount);
return mount;
}
return null;
};
const waitForMount = async (maxAttempts = 40) => {
for (let i = 0; i < maxAttempts; i++) {
const m = getMount();
if (m) return m;
await new Promise(r => setTimeout(r, 250));
}
return null;
};
const renderComments = (children, postAuthor) => {
const container = document.createElement('div');
container.className = 'os-comment-list';
for (const child of children) {
if (child.kind === 'more') {
const { count, children: moreIds } = child.data;
if (!moreIds?.length) continue;
const btn = document.createElement('button');
btn.className = 'os-load-more';
btn.textContent = `Load more comments (${count || moreIds.length})`;
btn.onclick = async () => {
btn.disabled = true;
btn.textContent = 'Loading...';
try {
const res = await OpenScript.fetch(
`https://www.reddit.com/api/morechildren.json?api_type=json&link_id=${activePostId}&children=${moreIds.slice(0, 20).join(',')}&sort=best`
);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json = await res.json();
const items = json?.json?.data?.things?.map(t => t.data) || [];
btn.replaceWith(renderFlatComments(items, postAuthor));
} catch {
btn.textContent = 'Failed to load comments';
}
};
container.append(btn);
continue;
}
const { id, author, score, created_utc, body_html, replies } = child.data;
if (!body_html) continue;
const el = document.createElement('div');
el.className = 'os-comment';
el.id = `os-c-${id}`;
const tagline = document.createElement('div');
tagline.className = 'os-comment-tagline';
const toggle = document.createElement('button');
toggle.className = 'os-collapse';
toggle.textContent = '[–]';
toggle.onclick = () => {
const isCol = el.classList.toggle('os-collapsed');
toggle.textContent = isCol ? '[+]' : '[–]';
};
const authorLink = document.createElement('a');
authorLink.className = `os-author${author === postAuthor ? ' os-op' : ''}`;
authorLink.href = `https://www.reddit.com/u/${author}`;
authorLink.target = '_blank';
authorLink.rel = 'noopener noreferrer';
authorLink.textContent = author;
const metaSpan = document.createElement('span');
metaSpan.className = 'os-score';
metaSpan.textContent = `• ${formatScore(score)} points • ${timeAgo(created_utc)}`;
tagline.append(toggle, authorLink, metaSpan);
const body = document.createElement('div');
body.className = 'os-body';
body.innerHTML = sanitizeHtml(body_html);
el.append(tagline, body);
if (replies?.data?.children?.length) {
const sub = renderComments(replies.data.children, postAuthor);
sub.className = 'os-replies';
el.append(sub);
}
container.append(el);
}
return container;
};
const renderFlatComments = (items, postAuthor) => {
const wrap = document.createDocumentFragment();
for (const item of items) {
if (!item.body_html) continue;
const el = document.createElement('div');
el.className = 'os-comment';
const tagline = document.createElement('div');
tagline.className = 'os-comment-tagline';
const authorLink = document.createElement('a');
authorLink.className = `os-author${item.author === postAuthor ? ' os-op' : ''}`;
authorLink.href = `https://www.reddit.com/u/${item.author}`;
authorLink.target = '_blank';
authorLink.rel = 'noopener noreferrer';
authorLink.textContent = item.author;
const meta = document.createElement('span');
meta.className = 'os-score';
meta.textContent = `• ${formatScore(item.score)} points • ${timeAgo(item.created_utc)}`;
tagline.append(authorLink, meta);
const body = document.createElement('div');
body.className = 'os-body';
body.innerHTML = sanitizeHtml(item.body_html);
el.append(tagline, body);
wrap.append(el);
}
return wrap;
};
const loadPostComments = async (post, postContainer) => {
postContainer.innerHTML = 'Loading Reddit comments...
';
try {
const res = await OpenScript.fetch(`https://www.reddit.com/comments/${post.id}.json?sort=best`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const [, commentsData] = await res.json();
const children = commentsData?.data?.children || [];
postContainer.innerHTML = '';
if (!children.length) {
postContainer.innerHTML = 'No comments in this thread yet.
';
return;
}
postContainer.append(renderComments(children, post.author));
} catch (err) {
postContainer.innerHTML = `Unable to load Reddit comments (${err.message}).
`;
}
};
const renderThread = (post, mount) => {
let contentArea = mount.querySelector('.os-content-area');
if (!contentArea) {
contentArea = document.createElement('div');
contentArea.className = 'os-content-area';
mount.append(contentArea);
}
contentArea.innerHTML = '';
const header = document.createElement('div');
header.className = 'os-header';
const left = document.createElement('div');
const title = document.createElement('a');
title.className = 'os-post-title';
title.href = `https://www.reddit.com${post.permalink}`;
title.target = '_blank';
title.rel = 'noopener noreferrer';
title.textContent = decodeHtml(post.title);
const meta = document.createElement('div');
meta.className = 'os-post-meta';
meta.textContent = `r/${post.subreddit} • Posted by u/${post.author} ${timeAgo(post.created_utc)} • ${formatScore(post.score)} points`;
left.append(title, meta);
header.append(left);
contentArea.append(header);
const commentsArea = document.createElement('div');
commentsArea.className = 'os-comments-area';
contentArea.append(commentsArea);
loadPostComments(post, commentsArea);
};
const renderTabs = (posts, mount) => {
mount.innerHTML = '';
const officialSub = getOfficialSub();
if (officialSub) {
posts.sort((a, b) => (a.subreddit.toLowerCase() === officialSub ? -1 : b.subreddit.toLowerCase() === officialSub ? 1 : 0));
}
const tabs = document.createElement('div');
tabs.className = 'os-tabs';
mount.append(tabs);
const activePost = posts.find(p => p.name === activePostId) || posts[0];
activePostId = activePost.name;
posts.forEach(post => {
const isOfficial = officialSub && post.subreddit.toLowerCase() === officialSub;
const tab = document.createElement('div');
tab.className = `os-tab${post.name === activePostId ? ' os-active' : ''}`;
tab.textContent = `r/${post.subreddit}`;
if (isOfficial) {
const off = document.createElement('span');
off.className = 'os-official-tag';
off.textContent = 'Official';
tab.append(off);
}
const badge = document.createElement('span');
badge.className = 'os-badge';
badge.textContent = `${formatScore(post.score)} ↑ • ${post.num_comments} 💬`;
tab.append(badge);
tab.onclick = () => {
if (activePostId === post.name) return;
activePostId = post.name;
tabs.querySelectorAll('.os-tab').forEach(t => t.classList.remove('os-active'));
tab.classList.add('os-active');
renderThread(post, mount);
};
tabs.append(tab);
});
renderThread(activePost, mount);
};
const updateForVideo = async videoId => {
ensureStyles();
cachedPosts = [];
activePostId = null;
const initialMount = getMount();
if (initialMount) {
initialMount.innerHTML = 'Searching Reddit for discussion threads...
';
}
try {
const res = await OpenScript.fetch(
`https://www.reddit.com/search.json?q=url:'${encodeURIComponent(videoId)}'&sort=top&type=link`
);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const posts = data?.data?.children?.map(c => c.data) || [];
if (videoId !== currentVideoId) return;
const mount = await waitForMount();
if (!mount || videoId !== currentVideoId) return;
if (!posts.length) {
mount.innerHTML = 'No Reddit discussions found for this video.
';
return;
}
cachedPosts = posts;
renderTabs(posts, mount);
} catch (err) {
const mount = await waitForMount();
if (mount && videoId === currentVideoId) {
mount.innerHTML = `
Could not search Reddit (${err.message}).
`;
mount.querySelector('.os-retry-btn')?.addEventListener('click', () => updateForVideo(videoId));
}
}
};
const getVideoId = () => {
const search = new URLSearchParams(location.search);
if (search.get('v')) return search.get('v');
const match = location.pathname.match(/\/shorts\/([a-zA-Z0-9_-]+)/);
return match ? match[1] : null;
};
const check = () => {
const id = getVideoId();
if (!id) {
currentVideoId = null;
const mount = document.getElementById(MOUNT_ID);
if (mount) mount.innerHTML = '';
return;
}
if (id === currentVideoId) {
if (cachedPosts.length && !document.getElementById(MOUNT_ID)?.hasChildNodes()) {
const mount = getMount();
if (mount) renderTabs(cachedPosts, mount);
}
return;
}
currentVideoId = id;
updateForVideo(id);
};
document.addEventListener('yt-navigate-finish', check);
setInterval(check, 1000);
check();