Jump to content

User:Ainali/bylines.js

From Wikipedia, the free encyclopedia
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.
// Fetch image author and license info, then display as byline below images
(function() {
    'use strict';

    // Function to fetch image metadata using the MediaWiki API
    async function fetchImageMetadata(imageTitle) {
        const url = `/w/api.php?action=query&titles=File:${encodeURIComponent(imageTitle)}&prop=imageinfo&iiprop=extmetadata&format=json&origin=*`;
        const response = await fetch(url);
        const data = await response.json();
        const pages = data.query.pages;
        const page = Object.values(pages)[0];

        if (page.imageinfo && page.imageinfo[0].extmetadata) {
            const extmetadata = page.imageinfo[0].extmetadata;
            const author = extmetadata.Artist ? extmetadata.Artist.value : "Unknown author";
            const license = extmetadata.LicenseShortName ? extmetadata.LicenseShortName.value : "Unknown license";
            const licenseUrl = extmetadata.LicenseUrl ? extmetadata.LicenseUrl.value : "#";
            return { author, license, licenseUrl };
        } else {
            return { author: "Unknown author", license: "Unknown license", licenseUrl: "#" };
        }
    }

    // Function to insert the byline next to the image
    function insertByline(image, author, license, licenseUrl) {
        const byline = document.createElement('div');
        byline.className = 'image-byline';
        byline.innerHTML = `${author} | <a href="${licenseUrl}" target="_blank">${license}</a>`;
        image.parentNode.insertBefore(byline, image.nextSibling);
    }

    // Function to process all images on the page
    async function processImages() {
        const images = document.querySelectorAll('img');
        for (let image of images) {
            const fileUrl = image.src;

            // Updated regex to capture the full file name including extension
            const fileNameMatch = fileUrl.match(/\/([a-zA-Z0-9_%.-]+\.(jpg|jpeg|png|svg|gif))/i);

            if (fileNameMatch) {
                const imageTitle = decodeURIComponent(fileNameMatch[1].replace(/_/g, ' '));
                const { author, license, licenseUrl } = await fetchImageMetadata(imageTitle);
                insertByline(image, author, license, licenseUrl);
            }
        }
    }

    // Wait for the page to fully load and then process the images
    window.addEventListener('load', processImages);
})();