Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- javascript:(function() {
- console.log('[Reddit BBCode Tool] Activated - Click copy buttons on posts/comments');
- const USE_DATA_URL_FOR_IMAGES = false;
- function htmlToBBCode(html) {
- const textarea = document.createElement('textarea');
- textarea.innerHTML = html;
- const decoded = textarea.value;
- return decoded
- .replace(/<h1>([\s\S]+?)<\/h1>/g, '[HEADING=1][b]$1[/b][/HEADING]\n\n')
- .replace(/<h2>([\s\S]+?)<\/h2>/g, '[HEADING=2][b]$1[/b][/HEADING]\n\n')
- .replace(/<h3>([\s\S]+?)<\/h3>/g, '[HEADING=3][b]$1[/b][/HEADING]\n\n')
- .replace(/<a href="([^"]+)"[^>]*>([\s\S]+?)<\/a>/g, (m, url, text) => {
- const cleanUrl = url.replace(/&/g, '&');
- const cleanText = text.replace(/<(?!\/?(?:b|i|s|u)\b)[^>]*>/gi, '');
- return `[u][url='${cleanUrl}']${cleanText}[/url][/u]`;
- })
- .replace(/<img src="([^"]+)"[^>]*>/g, '[img]$1[/img]')
- .replace(/<(b|strong)>([^<]+)<\/(b|strong)>/g, '[b]$2[/b]')
- .replace(/<(i|em)>([^<]+)<\/(i|em)>/g, '[i]$2[/i]')
- .replace(/<s>([^<]+)<\/s>/g, '[s]$1[/s]')
- .replace(/<blockquote>([\s\S]+?)<\/blockquote>/g, '[quote]$1[/quote]')
- .replace(/<pre>([\s\S]+?)<\/pre>/g, '[code]$1[/code]')
- .replace(/<code>([^<]+)<\/code>/g, '[icode]$1[/icode]')
- .replace(/<ol>([\s\S]+?)<\/ol>/g, (match, listContent) => '[LIST=1]\n' + listContent.replace(/<li>([\s\S]+?)<\/li>/g, '[*] $1\n') + '[/LIST]')
- .replace(/<ul>([\s\S]+?)<\/ul>/g, (match, listContent) => '[LIST]\n' + listContent.replace(/<li>([\s\S]+?)<\/li>/g, '[*] $1\n') + '[/LIST]')
- .replace(/<\/p>|<\s*br\s*\/?>/gi, '\n')
- .replace(/<\/?[^>]+>/g, '')
- .replace(/&/g, '&')
- .replace(/\n{3,}/g, '\n\n')
- .replace(/^\s+|\s+$/g, '');
- }
- function extractTextWithLinks(html) {
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- let text = doc.body.innerText.trim();
- const links = Array.from(doc.body.querySelectorAll('a'));
- const images = Array.from(doc.body.querySelectorAll('img'));
- let reconstructedText = text;
- links.forEach(link => {
- const linkText = link.textContent.trim();
- const linkUrl = link.href;
- reconstructedText = reconstructedText.replace(linkText, `[u][url]${linkUrl}[/url][/u]`);
- });
- images.forEach(image => {
- let src = image.src;
- if (USE_DATA_URL_FOR_IMAGES) {
- src = image.getAttribute('data-url') || src.replace(/preview\\.redd\\.it/, 'i.redd.it');
- }
- reconstructedText += `\n[img]${src}[/img]`;
- });
- return reconstructedText.trim();
- }
- function extractPostUrl(element) {
- return element.querySelector('a.bylink[href*="/comments/"]')?.href || element.querySelector('a.title[href*="/comments/"]')?.href || (element.hasAttribute('data-permalink') ? `https://www.reddit.com${element.getAttribute('data-permalink')}` : window.location.href);
- }
- function getParentComments(commentElement, maxDepth = 10) {
- const parents = [];
- const seenIds = new Set();
- let currentComment = commentElement.closest('.thing.comment, shreddit-comment');
- while (currentComment && parents.length < maxDepth) {
- const parentContainer = currentComment.parentElement.closest('.sitetable.listing, .child') || currentComment.parentElement.closest('shreddit-comment');
- if (!parentContainer) break;
- const parentComment = parentContainer.parentElement.closest('.thing.comment, shreddit-comment');
- if (!parentComment) break;
- const commentId = parentComment.id || parentComment.getAttribute('data-fullname');
- if (seenIds.has(commentId)) break;
- seenIds.add(commentId);
- const datetime = parentComment.querySelector('time')?.getAttribute('title') || parentComment.querySelector('time')?.getAttribute('datetime') || 'Unknown';
- const contentHtml = parentComment.querySelector('.md, div[slot="comment"]');
- const permalink = parentComment.querySelector('a.bylink')?.href || (parentComment.getAttribute('permalink') ? `https://www.reddit.com${parentComment.getAttribute('permalink')}` : window.location.href);
- const contentText = contentHtml ? extractTextWithLinks(contentHtml.innerHTML) : 'No content';
- const contentBBCode = htmlToBBCode(contentText);
- parents.unshift({ permalink, spoilerContent: `[spoiler="text"]\nCommented on ${datetime}\n\n${contentBBCode}\n[/spoiler]` });
- currentComment = parentComment;
- }
- return parents;
- }
- function createDepthDropdown(maxDepth, callback, button) {
- const existingDropdown = document.querySelector('.depth-dropdown');
- if (existingDropdown) existingDropdown.remove();
- const dropdown = document.createElement('select');
- dropdown.className = 'depth-dropdown';
- dropdown.style.position = 'absolute';
- dropdown.style.marginLeft = '5px';
- dropdown.style.padding = '2px';
- dropdown.style.fontSize = '12px';
- for (let i = 0; i <= maxDepth; i++) {
- const option = document.createElement('option');
- option.value = i;
- option.textContent = i === 0 ? 'Only this' : `${i} parent${i > 1 ? 's' : ''}`;
- dropdown.appendChild(option);
- }
- dropdown.addEventListener('change', () => {
- callback(parseInt(dropdown.value));
- dropdown.remove();
- });
- dropdown.addEventListener('blur', () => dropdown.remove());
- button.insertAdjacentElement('afterend', dropdown);
- dropdown.focus();
- }
- function createCopyButtons(element) {
- const existingButtons = element.querySelectorAll('.copy-btn, .nested-btn');
- existingButtons.forEach(btn => btn.remove());
- const copyButton = document.createElement('button');
- copyButton.textContent = '📋';
- copyButton.title = 'Copy content to BBCode';
- copyButton.className = 'copy-btn';
- copyButton.style.cssText = 'cursor:pointer;background:green;color:white;margin-left:5px;padding:2px 6px;border:none;border-radius:4px;';
- const nestedButton = document.createElement('button');
- nestedButton.textContent = '📋';
- nestedButton.title = 'Copy content with nested parents';
- nestedButton.className = 'nested-btn';
- nestedButton.style.cssText = 'cursor:pointer;background:blue;color:white;margin-left:5px;padding:2px 6px;border:none;border-radius:4px;';
- if (element.tagName.toLowerCase() === 'shreddit-post' || element.classList.contains('thing') && element.classList.contains('link')) {
- const url = extractPostUrl(element);
- let header = '', body = '', images = new Set();
- const title = element.querySelector('h1[slot="title"], .title > a')?.textContent.trim() || '';
- const flair = element.querySelector('.linkflairlabel span')?.textContent.trim() || '';
- const datetime = element.querySelector('time')?.getAttribute('title') || element.querySelector('time')?.getAttribute('datetime') || 'Unknown';
- const videoUrl = element.dataset.url || element.getAttribute('data-url');
- header = `${flair ? `[i][${flair}][/i] ` : ''}[b]${title}[/b]\n\n${url}\n\n`;
- Array.from(element.querySelectorAll('gallery-carousel li img, .media-preview img'))
- .forEach(img => {
- let src = img.src;
- if (USE_DATA_URL_FOR_IMAGES) {
- src = img.getAttribute('data-url') || src.replace(/preview\\.redd\\.it/, 'i.redd.it');
- }
- if (!src.includes('redditstatic.com/video-') && !src.includes('old.reddit.com/static/checkmark.svg')) {
- images.add(src);
- }
- });
- const textBody = element.querySelector('div[slot="text-body"], .md');
- if (textBody) body += htmlToBBCode(extractTextWithLinks(textBody.innerHTML));
- const imgSection = Array.from(images).map(u => `[img]${u}[/img]`).join('\n');
- const mediaContent = [ `Posted on ${datetime}`, ...(imgSection ? [imgSection] : []), ...(videoUrl ? [videoUrl] : []) ];
- const fullPayload = `${header}[spoiler="text"]\n${mediaContent.join('\n\n')}\n\n${body.trim()}\n[/spoiler]`;
- copyButton.addEventListener('click', (e) => {
- e.preventDefault();
- e.stopPropagation();
- navigator.clipboard.writeText(fullPayload.replace(/\n{3,}/g, '\n\n'))
- .then(() => showToast('Post copied!'))
- .catch(err => console.error('[Reddit BBCode Tool] Copy failed:', err));
- });
- nestedButton.style.display = 'none';
- const target = element.querySelector('div[slot="credit-bar"], .tagline') || element;
- target.appendChild(copyButton);
- target.appendChild(nestedButton);
- } else if (element.tagName.toLowerCase() === 'shreddit-comment' || element.classList.contains('comment')) {
- const permalink = element.getAttribute('permalink') ? `https://www.reddit.com${element.getAttribute('permalink')}` : element.querySelector('a.bylink')?.href || window.location.href;
- const contentHtml = element.querySelector('div[slot="comment"], .md');
- if (!contentHtml) {
- console.log('[Reddit BBCode Tool] No content found for comment');
- return;
- }
- const datetime = element.querySelector('time')?.getAttribute('title') || element.querySelector('time')?.getAttribute('datetime') || 'Unknown';
- const contentText = extractTextWithLinks(contentHtml.innerHTML);
- const contentBBCode = htmlToBBCode(contentText);
- const spoilerContent = `[spoiler="text"]\nCommented on ${datetime}\n\n${contentBBCode}\n[/spoiler]`;
- copyButton.addEventListener('click', (e) => {
- e.preventDefault();
- e.stopPropagation();
- navigator.clipboard.writeText(`${permalink}\n${spoilerContent}`.replace(/\n{3,}/g, '\n\n'))
- .then(() => showToast('Comment copied!'))
- .catch(err => console.error('[Reddit BBCode Tool] Copy failed:', err));
- });
- nestedButton.addEventListener('click', (e) => {
- e.preventDefault();
- e.stopPropagation();
- const parents = getParentComments(element);
- const maxDepth = parents.length;
- createDepthDropdown(maxDepth, (depth) => {
- const items = [ ...parents.slice(0, depth), { permalink, spoilerContent } ];
- const payload = items
- .map((item, index) => {
- const indent = '│ '.repeat(index);
- const commentLines = `${item.permalink}\n${item.spoilerContent}`.split('\n');
- return commentLines.map(line => `${indent}${line}`).join('\n');
- })
- .join('\n\n').replace(/\n{3,}/g, '\n\n');
- navigator.clipboard.writeText(payload)
- .then(() => showToast(`Comment with ${depth} parent${depth === 1 ? '' : 's'} copied!`))
- .catch(err => console.error('[Reddit BBCode Tool] Nested copy failed:', err));
- }, nestedButton);
- });
- const target = element.querySelector('div[slot="actionRow"], .tagline') || element;
- target.appendChild(copyButton);
- target.appendChild(nestedButton);
- }
- }
- function showToast(message) {
- const toast = document.createElement('div');
- toast.textContent = message;
- toast.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);padding:10px;border-radius:5px;background:#fff;color:#000;z-index:1000;box-shadow:0 0 10px rgba(0,0,0,0.2);';
- document.body.appendChild(toast);
- setTimeout(() => toast.remove(), 2000);
- }
- document.querySelectorAll('shreddit-post, shreddit-comment, .thing.link, .thing.comment').forEach(createCopyButtons);
- })();
Advertisement
Add Comment
Please, Sign In to add comment