User:Euphoria/common.js

From Test Wiki
Revision as of 06:28, 23 December 2023 by Euphoria (talk | contribs) (addButtonToSidebar)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// ==UserScript==
// @name        Find Articles Without Images
// @namespace   WikipediaUserScripts
// @description Finds articles in a category that lack images and logs them to the console.
// @include     /^https:\/\/en\.wikipedia\.org\/wiki\/Category:.+/
// @version     1
// @grant       none
// ==/UserScript==

(function() {
    'use strict';

    // Function to check if a page has images
    async function checkIfPageHasImage(pageTitle) {
        const endpoint = `https://en.wikipedia.org/w/api.php?action=query&titles=${encodeURIComponent(pageTitle)}&prop=images&format=json&origin=*`;
        const response = await fetch(endpoint);
        const data = await response.json();
        const page = data.query.pages[Object.keys(data.query.pages)[0]];
        return page.hasOwnProperty('images');
    }

    // Main function to find articles without images
    async function findArticlesWithoutImages() {
        const categoryTitle = document.getElementById('firstHeading').innerText;
        const endpoint = `https://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=${encodeURIComponent(categoryTitle)}&cmlimit=max&format=json&origin=*`;
        const response = await fetch(endpoint);
        const data = await response.json();
        const articles = data.query.categorymembers;

        for (const article of articles) {
            const hasImage = await checkIfPageHasImage(article.title);
            if (!hasImage) {
                console.log(`Article without image found: ${article.title}`);
            }
        }
    }

    // Add a button to the sidebar
    function addButtonToSidebar() {
        var sidebar = document.getElementById('mw-panel');

        if (sidebar) {
            var button = document.createElement('button');
            button.textContent = 'Find Articles Without Images';
            button.style.margin = '5px';
            button.style.width = '90%';
            button.onclick = findArticlesWithoutImages;

            var container = document.createElement('div');
            container.style.textAlign = 'center';
            container.appendChild(button);

            sidebar.appendChild(container);
        }
    }

    // Add the button when the script loads
    addButtonToSidebar();

})();