User:Ainali/bylines.js
Appearance
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.
This code will be executed when previewing this page.
Documentation for this user script can be added at User:Ainali/bylines. This user script seems to have an accompanying .css page at User:Ainali/bylines.css.
// 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);
})();