Wikimedia Commons: files page: add categories near every file name

In your list of uploaded files you will see clickable categories

  1. // ==UserScript==
  2. // @name Wikimedia Commons: files page: add categories near every file name
  3. // @description In your list of uploaded files you will see clickable categories
  4. // @namespace Violentmonkey Scripts
  5. // @version 1.5
  6. // @author Vitaly Zdanevich
  7. // @match https://commons.wikimedia.org/w/index.php?title=Special:ListFiles/*
  8. // @supportURL https://gitlab.com/vitaly-zdanevich-userscripts/uploadPageShowCategories
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. let fileNames = '';
  14. const fileNamesArr = [];
  15.  
  16. const files = document.querySelectorAll('.TablePager_col_img_name > a[href^="/wiki/File:"]');
  17.  
  18. files.forEach((f, i) => {
  19. const fileName = nodeToFilename(f);
  20.  
  21. fileNames += fileName
  22. if (i > 0 && (i+1) % 10 === 0) { // 50 is API limit, but 10 against "414 URI Too Long"
  23. fileNamesArr.push(fileNames);
  24. fileNames = '';
  25. } else {
  26. fileNames += '|'
  27. }
  28. });
  29.  
  30. fileNamesArr.forEach(f => {
  31. const url = 'https://commons.wikimedia.org/w/api.php?action=query&format=json&prop=categories&formatversion=2&cllimit=max&clshow=!hidden&titles=' + f + '&origin=*';
  32.  
  33. fetch(url).then(resp => resp.json()).then(data => {
  34. const result = {};
  35.  
  36. // Process the API response
  37. if (data.query && data.query.pages) {
  38. data.query.pages.forEach(page => {
  39.  
  40. if (page.categories) {
  41. const categories = page.categories.map(category => {
  42. return category.title;
  43. });
  44. result[page.title] = categories;
  45. }
  46.  
  47. });
  48. }
  49.  
  50. files.forEach(f => {
  51. const fileName = nodeToFilename(f);
  52. if (fileName in result) {
  53. const categories = result[fileName];
  54.  
  55. // Create links for each category and append them to the current link's parent element
  56. categories.forEach(category => {
  57. const categoryLink = $('<a>', {
  58. text: category.replace(/^Category:/g, ''),
  59. href: 'https://commons.wikimedia.org/wiki/' + category,
  60. css: { display: 'block', fontSize: 'small', marginLeft: '10px' } // Add some style for better appearance
  61. });
  62. $(f).parent().append(categoryLink);
  63. });
  64. }
  65. });
  66. });
  67. })
  68.  
  69. })();
  70.  
  71. // Extract the "File:..." part from the link href attribute
  72. function nodeToFilename(node) {
  73. const fileName = node.href.split('/').pop();
  74. return decodeURIComponent(fileName).replace(/_/g, ' '); // Replace underscores with spaces
  75. // For smaller response without "normalized" array
  76. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址