xxxxxxxxxx
72
// jshint esversion:8
// A2Z F24
// Daniel Shiffman
// https://github.com/Programming-from-A-to-Z/A2Z-F24
// Documentation for Wikipedia API
// https://www.mediawiki.org/wiki/API:Main_page
// Input from user
let input;
function setup() {
noCanvas();
// Grab the input and button from HTML
input = select("#search");
let button = select("#submit");
// Attach a callback to button press
button.mousePressed(search);
}
// Run the API call
async function search() {
let term = input.value();
// URL for querying wikipedia
let url =
"https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" +
"&origin=*&search=" +
term;
// Dealing with CORS problem and Wikipedia
// url = 'https://cors-anywhere.herokuapp.com/' + url;
// Query the URL, set a callback
let response = await fetch(url);
let data = await response.json();
console.log(data);
// Look at article list
let articles = data[1];
// Make a clickable link for each one
for (let article of articles) {
// We could also have this example just link to the articles themselves
// let link = 'http://en.wikipedia.org/w/index.php?title=' + articles[i];
// let a = createA(link, articles[i]);
// But we are doing something fancier and excuting another query!
let li = createElement("li", article + " ");
let button = createButton('more');
button.parent(li);
li.parent("list");
button.mousePressed(async () => {
let url =
"https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&origin=*";
// Wikipedia wants underscores instead of spaces
article = article.replace(/\s+/, "_");
let newUrl = `${url}&titles=${article}`;
let response = await fetch(newUrl);
let data = await response.json();
let page = data.query.pages;
// The content is in the page's ID #, but we don't actually know the ID number
// But it always comes first, this is a goofy way to get it
let id = Object.keys(page)[0];
// Look at the actual content
let txt = page[id].revisions[0]["*"];
// Show in on the HTML page
createP(txt);
});
}
}