This is an old revision of this page, as edited by Polygnotus(talk | contribs) at 14:34, 13 April 2025(←Created page with '// Wikipedia Category Items Copier // This script adds two buttons to Wikipedia category pages: // 1. "Copy Items" - Copies all items in the current category // 2. "Copy All Items" - Copies all items in the current category and its subcategories // Check if we're on a Wikipedia category page if (!window.___location.href.includes('/wiki/Category:')) { alert('This script only works on Wikipedia category pages.'); } else { // Create a container for our b...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.Revision as of 14:34, 13 April 2025 by Polygnotus(talk | contribs)(←Created page with '// Wikipedia Category Items Copier // This script adds two buttons to Wikipedia category pages: // 1. "Copy Items" - Copies all items in the current category // 2. "Copy All Items" - Copies all items in the current category and its subcategories // Check if we're on a Wikipedia category page if (!window.___location.href.includes('/wiki/Category:')) { alert('This script only works on Wikipedia category pages.'); } else { // Create a container for our b...')
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Wikipedia Category Items Copier// This script adds two buttons to Wikipedia category pages:// 1. "Copy Items" - Copies all items in the current category// 2. "Copy All Items" - Copies all items in the current category and its subcategories// Check if we're on a Wikipedia category pageif(!window.___location.href.includes('/wiki/Category:')){alert('This script only works on Wikipedia category pages.');}else{// Create a container for our buttonsconstcontainer=document.createElement('div');container.style.padding='10px';container.style.margin='10px 0';container.style.backgroundColor='#f8f9fa';container.style.border='1px solid #a2a9b1';container.style.borderRadius='3px';// Create the "Copy Items" buttonconstcopyItemsBtn=document.createElement('button');copyItemsBtn.textContent='Copy Items from this Category';copyItemsBtn.style.marginRight='10px';copyItemsBtn.style.padding='8px 12px';copyItemsBtn.style.cursor='pointer';// Create the "Copy All Items" buttonconstcopyAllItemsBtn=document.createElement('button');copyAllItemsBtn.textContent='Copy Items from All Subcategories';copyAllItemsBtn.style.padding='8px 12px';copyAllItemsBtn.style.cursor='pointer';// Create status textconststatusText=document.createElement('div');statusText.style.marginTop='10px';statusText.style.color='#555';// Add buttons to containercontainer.appendChild(copyItemsBtn);container.appendChild(copyAllItemsBtn);container.appendChild(statusText);// Insert container after the page titleconstpageTitleHeading=document.querySelector('.mw-first-heading');if(pageTitleHeading){pageTitleHeading.parentNode.insertBefore(container,pageTitleHeading.nextSibling);}else{document.querySelector('#content').prepend(container);}// Function to get items from the current category pagefunctiongetItemsFromCurrentPage(){constitems=[];// Get all links from the category page that aren't subcategoriesconstitemLinks=Array.from(document.querySelectorAll('#mw-pages a'));itemLinks.forEach(link=>{// Skip unnecessary links like "previous page" or "next page"if(link.parentElement.id==='mw-pages-prev'||link.parentElement.id==='mw-pages-next'||link.textContent.trim()==='next page'||link.textContent.trim()==='previous page'){return;}// Skip links from the navigation sectionsif(link.closest('.mw-normal-catlinks')||link.closest('.noprint')||link.closest('.catlinks')){return;}// Add the item to our listitems.push(link.textContent.trim());});returnitems;}// Function to copy text to clipboard (Firefox on Pop OS compatible)functioncopyToClipboard(text){returnnewPromise((resolve,reject)=>{// Create a temporary textarea elementconsttextarea=document.createElement('textarea');textarea.value=text;// Make the textarea invisible but present in the DOMtextarea.style.position='fixed';textarea.style.opacity='0';document.body.appendChild(textarea);// Select and copytextarea.select();try{// Try the modern clipboard API firstif(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(text).then(()=>{document.body.removeChild(textarea);resolve(true);}).catch(err=>{// Fall back to document.execCommandconstsuccess=document.execCommand('copy');document.body.removeChild(textarea);if(success){resolve(true);}else{reject(newError('Unable to copy to clipboard'));}});}else{// Use execCommand as fallbackconstsuccess=document.execCommand('copy');document.body.removeChild(textarea);if(success){resolve(true);}else{reject(newError('Unable to copy to clipboard'));}}}catch(err){document.body.removeChild(textarea);reject(err);}});}// Function to get subcategories from the current pagefunctiongetSubcategories(){constsubcategories=[];constsubcategoryLinks=document.querySelectorAll('#mw-subcategories a');subcategoryLinks.forEach(link=>{// Skip "previous page" or "next page" linksif(link.parentElement.id==='mw-subcategories-prev'||link.parentElement.id==='mw-subcategories-next'||link.textContent.trim()==='next page'||link.textContent.trim()==='previous page'){return;}// Only include links to category pagesif(link.href&&link.href.includes('/wiki/Category:')){subcategories.push(link.href);}});returnsubcategories;}// Function to fetch and process a category pageasyncfunctionfetchCategoryPage(url){statusText.textContent=`Fetching: ${url}`;try{// Add a small delay to avoid hammering the serverawaitnewPromise(resolve=>setTimeout(resolve,500));constresponse=awaitfetch(url);consthtml=awaitresponse.text();// Create a temporary element to parse the HTMLconsttempDiv=document.createElement('div');tempDiv.innerHTML=html;// Get items from the pageconstitems=[];constitemLinks=tempDiv.querySelectorAll('#mw-pages a');itemLinks.forEach(link=>{// Skip unnecessary linksif(link.parentElement.id==='mw-pages-prev'||link.parentElement.id==='mw-pages-next'||link.textContent.trim()==='next page'||link.textContent.trim()==='previous page'){return;}// Add the item to our listitems.push(link.textContent.trim());});returnitems;}catch(error){console.error('Error fetching category page:',error);statusText.textContent=`Error fetching ${url}: ${error.message}`;return[];}}// Handle "Copy Items" button clickcopyItemsBtn.addEventListener('click',async()=>{statusText.textContent='Gathering items from this category...';constitems=getItemsFromCurrentPage();if(items.length===0){statusText.textContent='No items found in this category.';return;}try{awaitcopyToClipboard(items.join('\n'));statusText.textContent=`Successfully copied ${items.length} items to clipboard.`;}catch(error){statusText.textContent=`Error copying to clipboard: ${error.message}`;console.error('Copy error:',error);}});// Handle "Copy All Items" button clickcopyAllItemsBtn.addEventListener('click',async()=>{statusText.textContent='Gathering items from all subcategories (this may take a while)...';// Get items from the current pageletallItems=getItemsFromCurrentPage();// Get subcategoriesconstsubcategories=getSubcategories();constprocessedCategories=newSet();// To avoid processing the same category twice// Process each subcategory (limited to avoid hammering the API)constMAX_SUBCATEGORIES=10;// Limit the number of subcategories to processfor(leti=0;i<Math.min(subcategories.length,MAX_SUBCATEGORIES);i++){constsubcategoryUrl=subcategories[i];if(!processedCategories.has(subcategoryUrl)){processedCategories.add(subcategoryUrl);constsubcategoryItems=awaitfetchCategoryPage(subcategoryUrl);allItems=allItems.concat(subcategoryItems);statusText.textContent=`Processed ${i+1}/${Math.min(subcategories.length,MAX_SUBCATEGORIES)} subcategories. Found ${allItems.length} items so far...`;}}if(subcategories.length>MAX_SUBCATEGORIES){statusText.textContent+=` (Limited to ${MAX_SUBCATEGORIES} subcategories to avoid overloading. Found ${allItems.length} items.)`;}// Deduplicate itemsconstuniqueItems=[...newSet(allItems)];if(uniqueItems.length===0){statusText.textContent='No items found in this category or its subcategories.';return;}try{awaitcopyToClipboard(uniqueItems.join('\n'));statusText.textContent=`Successfully copied ${uniqueItems.length} unique items to clipboard.`;}catch(error){statusText.textContent=`Error copying to clipboard: ${error.message}`;console.error('Copy error:',error);}});console.log('Wikipedia Category Copier script has been loaded successfully!');}