Guest User

Untitled

a guest
May 13th, 2025
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. javascript:(function() {
  2.   console.log('[Reddit BBCode Tool] Activated - Click copy buttons on posts/comments');
  3.   const USE_DATA_URL_FOR_IMAGES = false;
  4.   function htmlToBBCode(html) {
  5.     const textarea = document.createElement('textarea');
  6.     textarea.innerHTML = html;
  7.     const decoded = textarea.value;
  8.     return decoded
  9.       .replace(/<h1>([\s\S]+?)<\/h1>/g, '[HEADING=1][b]$1[/b][/HEADING]\n\n')
  10.       .replace(/<h2>([\s\S]+?)<\/h2>/g, '[HEADING=2][b]$1[/b][/HEADING]\n\n')
  11.       .replace(/<h3>([\s\S]+?)<\/h3>/g, '[HEADING=3][b]$1[/b][/HEADING]\n\n')
  12.       .replace(/<a href="([^"]+)"[^>]*>([\s\S]+?)<\/a>/g, (m, url, text) => {
  13.         const cleanUrl = url.replace(/&/g, '&amp;');
  14.         const cleanText = text.replace(/<(?!\/?(?:b|i|s|u)\b)[^>]*>/gi, '');
  15.         return `[u][url='${cleanUrl}']${cleanText}[/url][/u]`;
  16.       })
  17.       .replace(/<img src="([^"]+)"[^>]*>/g, '[img]$1[/img]')
  18.       .replace(/<(b|strong)>([^<]+)<\/(b|strong)>/g, '[b]$2[/b]')
  19.       .replace(/<(i|em)>([^<]+)<\/(i|em)>/g, '[i]$2[/i]')
  20.       .replace(/<s>([^<]+)<\/s>/g, '[s]$1[/s]')
  21.       .replace(/<blockquote>([\s\S]+?)<\/blockquote>/g, '[quote]$1[/quote]')
  22.       .replace(/<pre>([\s\S]+?)<\/pre>/g, '[code]$1[/code]')
  23.       .replace(/<code>([^<]+)<\/code>/g, '[icode]$1[/icode]')
  24.       .replace(/<ol>([\s\S]+?)<\/ol>/g, (match, listContent) => '[LIST=1]\n' + listContent.replace(/<li>([\s\S]+?)<\/li>/g, '[*] $1\n') + '[/LIST]')
  25.       .replace(/<ul>([\s\S]+?)<\/ul>/g, (match, listContent) => '[LIST]\n' + listContent.replace(/<li>([\s\S]+?)<\/li>/g, '[*] $1\n') + '[/LIST]')
  26.       .replace(/<\/p>|<\s*br\s*\/?>/gi, '\n')
  27.       .replace(/<\/?[^>]+>/g, '')
  28.       .replace(/&amp;/g, '&')
  29.       .replace(/\n{3,}/g, '\n\n')
  30.       .replace(/^\s+|\s+$/g, '');
  31.   }
  32.   function extractTextWithLinks(html) {
  33.     const parser = new DOMParser();
  34.     const doc = parser.parseFromString(html, 'text/html');
  35.     let text = doc.body.innerText.trim();
  36.     const links = Array.from(doc.body.querySelectorAll('a'));
  37.     const images = Array.from(doc.body.querySelectorAll('img'));
  38.     let reconstructedText = text;
  39.     links.forEach(link => {
  40.       const linkText = link.textContent.trim();
  41.       const linkUrl = link.href;
  42.       reconstructedText = reconstructedText.replace(linkText, `[u][url]${linkUrl}[/url][/u]`);
  43.     });
  44.     images.forEach(image => {
  45.       let src = image.src;
  46.       if (USE_DATA_URL_FOR_IMAGES) {
  47.         src = image.getAttribute('data-url') || src.replace(/preview\\.redd\\.it/, 'i.redd.it');
  48.       }
  49.       reconstructedText += `\n[img]${src}[/img]`;
  50.     });
  51.     return reconstructedText.trim();
  52.   }
  53.   function extractPostUrl(element) {
  54.     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);
  55.   }
  56.   function getParentComments(commentElement, maxDepth = 10) {
  57.     const parents = [];
  58.     const seenIds = new Set();
  59.     let currentComment = commentElement.closest('.thing.comment, shreddit-comment');
  60.     while (currentComment && parents.length < maxDepth) {
  61.       const parentContainer = currentComment.parentElement.closest('.sitetable.listing, .child') || currentComment.parentElement.closest('shreddit-comment');
  62.       if (!parentContainer) break;
  63.       const parentComment = parentContainer.parentElement.closest('.thing.comment, shreddit-comment');
  64.       if (!parentComment) break;
  65.       const commentId = parentComment.id || parentComment.getAttribute('data-fullname');
  66.       if (seenIds.has(commentId)) break;
  67.       seenIds.add(commentId);
  68.       const datetime = parentComment.querySelector('time')?.getAttribute('title') || parentComment.querySelector('time')?.getAttribute('datetime') || 'Unknown';
  69.       const contentHtml = parentComment.querySelector('.md, div[slot="comment"]');
  70.       const permalink = parentComment.querySelector('a.bylink')?.href || (parentComment.getAttribute('permalink') ? `https://www.reddit.com${parentComment.getAttribute('permalink')}` : window.location.href);
  71.       const contentText = contentHtml ? extractTextWithLinks(contentHtml.innerHTML) : 'No content';
  72.       const contentBBCode = htmlToBBCode(contentText);
  73.       parents.unshift({ permalink, spoilerContent: `[spoiler="text"]\nCommented on ${datetime}\n\n${contentBBCode}\n[/spoiler]` });
  74.       currentComment = parentComment;
  75.     }
  76.     return parents;
  77.   }
  78.   function createDepthDropdown(maxDepth, callback, button) {
  79.     const existingDropdown = document.querySelector('.depth-dropdown');
  80.     if (existingDropdown) existingDropdown.remove();
  81.     const dropdown = document.createElement('select');
  82.     dropdown.className = 'depth-dropdown';
  83.     dropdown.style.position = 'absolute';
  84.     dropdown.style.marginLeft = '5px';
  85.     dropdown.style.padding = '2px';
  86.     dropdown.style.fontSize = '12px';
  87.     for (let i = 0; i <= maxDepth; i++) {
  88.       const option = document.createElement('option');
  89.       option.value = i;
  90.       option.textContent = i === 0 ? 'Only this' : `${i} parent${i > 1 ? 's' : ''}`;
  91.       dropdown.appendChild(option);
  92.     }
  93.     dropdown.addEventListener('change', () => {
  94.       callback(parseInt(dropdown.value));
  95.       dropdown.remove();
  96.     });
  97.     dropdown.addEventListener('blur', () => dropdown.remove());
  98.     button.insertAdjacentElement('afterend', dropdown);
  99.     dropdown.focus();
  100.   }
  101.   function createCopyButtons(element) {
  102.     const existingButtons = element.querySelectorAll('.copy-btn, .nested-btn');
  103.     existingButtons.forEach(btn => btn.remove());
  104.     const copyButton = document.createElement('button');
  105.     copyButton.textContent = '📋';
  106.     copyButton.title = 'Copy content to BBCode';
  107.     copyButton.className = 'copy-btn';
  108.     copyButton.style.cssText = 'cursor:pointer;background:green;color:white;margin-left:5px;padding:2px 6px;border:none;border-radius:4px;';
  109.     const nestedButton = document.createElement('button');
  110.     nestedButton.textContent = '📋';
  111.     nestedButton.title = 'Copy content with nested parents';
  112.     nestedButton.className = 'nested-btn';
  113.     nestedButton.style.cssText = 'cursor:pointer;background:blue;color:white;margin-left:5px;padding:2px 6px;border:none;border-radius:4px;';
  114.     if (element.tagName.toLowerCase() === 'shreddit-post' || element.classList.contains('thing') && element.classList.contains('link')) {
  115.       const url = extractPostUrl(element);
  116.       let header = '', body = '', images = new Set();
  117.       const title = element.querySelector('h1[slot="title"], .title > a')?.textContent.trim() || '';
  118.       const flair = element.querySelector('.linkflairlabel span')?.textContent.trim() || '';
  119.       const datetime = element.querySelector('time')?.getAttribute('title') || element.querySelector('time')?.getAttribute('datetime') || 'Unknown';
  120.       const videoUrl = element.dataset.url || element.getAttribute('data-url');
  121.       header = `${flair ? `[i][${flair}][/i] ` : ''}[b]${title}[/b]\n\n${url}\n\n`;
  122.       Array.from(element.querySelectorAll('gallery-carousel li img, .media-preview img'))
  123.         .forEach(img => {
  124.           let src = img.src;
  125.           if (USE_DATA_URL_FOR_IMAGES) {
  126.             src = img.getAttribute('data-url') || src.replace(/preview\\.redd\\.it/, 'i.redd.it');
  127.           }
  128.           if (!src.includes('redditstatic.com/video-') && !src.includes('old.reddit.com/static/checkmark.svg')) {
  129.             images.add(src);
  130.           }
  131.         });
  132.       const textBody = element.querySelector('div[slot="text-body"], .md');
  133.       if (textBody) body += htmlToBBCode(extractTextWithLinks(textBody.innerHTML));
  134.       const imgSection = Array.from(images).map(u => `[img]${u}[/img]`).join('\n');
  135.       const mediaContent = [ `Posted on ${datetime}`, ...(imgSection ? [imgSection] : []), ...(videoUrl ? [videoUrl] : []) ];
  136.       const fullPayload = `${header}[spoiler="text"]\n${mediaContent.join('\n\n')}\n\n${body.trim()}\n[/spoiler]`;
  137.       copyButton.addEventListener('click', (e) => {
  138.         e.preventDefault();
  139.         e.stopPropagation();
  140.         navigator.clipboard.writeText(fullPayload.replace(/\n{3,}/g, '\n\n'))
  141.           .then(() => showToast('Post copied!'))
  142.           .catch(err => console.error('[Reddit BBCode Tool] Copy failed:', err));
  143.       });
  144.       nestedButton.style.display = 'none';
  145.       const target = element.querySelector('div[slot="credit-bar"], .tagline') || element;
  146.       target.appendChild(copyButton);
  147.       target.appendChild(nestedButton);
  148.     } else if (element.tagName.toLowerCase() === 'shreddit-comment' || element.classList.contains('comment')) {
  149.       const permalink = element.getAttribute('permalink') ? `https://www.reddit.com${element.getAttribute('permalink')}` : element.querySelector('a.bylink')?.href || window.location.href;
  150.       const contentHtml = element.querySelector('div[slot="comment"], .md');
  151.       if (!contentHtml) {
  152.         console.log('[Reddit BBCode Tool] No content found for comment');
  153.         return;
  154.       }
  155.       const datetime = element.querySelector('time')?.getAttribute('title') || element.querySelector('time')?.getAttribute('datetime') || 'Unknown';
  156.       const contentText = extractTextWithLinks(contentHtml.innerHTML);
  157.       const contentBBCode = htmlToBBCode(contentText);
  158.       const spoilerContent = `[spoiler="text"]\nCommented on ${datetime}\n\n${contentBBCode}\n[/spoiler]`;
  159.       copyButton.addEventListener('click', (e) => {
  160.         e.preventDefault();
  161.         e.stopPropagation();
  162.         navigator.clipboard.writeText(`${permalink}\n${spoilerContent}`.replace(/\n{3,}/g, '\n\n'))
  163.           .then(() => showToast('Comment copied!'))
  164.           .catch(err => console.error('[Reddit BBCode Tool] Copy failed:', err));
  165.       });
  166.       nestedButton.addEventListener('click', (e) => {
  167.         e.preventDefault();
  168.         e.stopPropagation();
  169.         const parents = getParentComments(element);
  170.         const maxDepth = parents.length;
  171.         createDepthDropdown(maxDepth, (depth) => {
  172.           const items = [ ...parents.slice(0, depth), { permalink, spoilerContent } ];
  173.           const payload = items
  174.             .map((item, index) => {
  175.               const indent = '│ '.repeat(index);
  176.               const commentLines = `${item.permalink}\n${item.spoilerContent}`.split('\n');
  177.               return commentLines.map(line => `${indent}${line}`).join('\n');
  178.             })
  179.             .join('\n\n').replace(/\n{3,}/g, '\n\n');
  180.           navigator.clipboard.writeText(payload)
  181.             .then(() => showToast(`Comment with ${depth} parent${depth === 1 ? '' : 's'} copied!`))
  182.             .catch(err => console.error('[Reddit BBCode Tool] Nested copy failed:', err));
  183.         }, nestedButton);
  184.       });
  185.       const target = element.querySelector('div[slot="actionRow"], .tagline') || element;
  186.       target.appendChild(copyButton);
  187.       target.appendChild(nestedButton);
  188.     }
  189.   }
  190.   function showToast(message) {
  191.     const toast = document.createElement('div');
  192.     toast.textContent = message;
  193.     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);';
  194.     document.body.appendChild(toast);
  195.     setTimeout(() => toast.remove(), 2000);
  196.   }
  197.   document.querySelectorAll('shreddit-post, shreddit-comment, .thing.link, .thing.comment').forEach(createCopyButtons);
  198. })();
Advertisement
Add Comment
Please, Sign In to add comment