P.12
Web APIで画像のURLを取得する
◼
コードにするとこんな感じ
P.12
getWikiMediaImage(fileTitle, thumbnailWidth, imageDom) {
const apiUrl =
`https://commons.wikimedia.org/w/api.php?action=query&titles=${fileTitle}&format=json&prop=imageinfo&iiprop=url|extmetadata
&origin=*`;
fetch(apiUrl + (thumbnailWidth == "" ? "" : `&iiurlwidth=${thumbnailWidth}`))
.then(response => response.json())
.then(data => {
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
const urlCat = thumbnailWidth == "" ? "url" : "thumburl";
if (pages[pageId].imageinfo !== undefined) {
const fileUrl = pages[pageId].imageinfo[0][urlCat];
const copyright = typeof (imageDom) == "string" ? document.getElementById(imageDom + "-copyright") :
undefined
imageDom = typeof (imageDom) == "string" ? document.getElementById(imageDom) : imageDom;
imageDom.src = fileUrl;
imageDom.setAttribute("src_org", pages[pageId].imageinfo[0].url);
imageDom.setAttribute("src_org", pages[pageId].imageinfo[0].url);
if (copyright !== undefined) {
let artist = pages[pageId].imageinfo[0].extmetadata.Artist.value
let license = pages[pageId].imageinfo[0].extmetadata.LicenseShortName.value
let html = `Image by ${artist}
${license}`
copyright.innerHTML = html
}
} else {
console.log("File Not Found:" + pages[pageId].title);
}
})
}