User:Polygnotus/Scripts/GetAPIBatch.js: Difference between revisions

Content deleted Content added
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 37:
margin-top: 0.5rem;
font-style: italic;
}
#article-content {
margin-top: 1rem;
max-height: 300px;
overflow-y: auto;
border: 1px solid #ccc;
padding: 10px;
}
#article-link {
display: block;
margin-top: 0.5rem;
}
`;
Line 61 ⟶ 50:
<div id="article-name"></div>
<button id="next-button">Next Word</button>
<a id="article-link" target="_blank">View full article</a>
<div id="article-content"></div>
<div id="debug-info"></div>
`;
Line 77 ⟶ 64:
this.debugElement = document.getElementById('debug-info');
this.articleNameElement = document.getElementById('article-name');
this.articleContentElement = document.getElementById('article-content');
this.articleLinkElement = document.getElementById('article-link');
 
this.nextButton.addEventListener('click', () => this.displayNextWorddisplayNextWordAndNavigate());
 
this.fetchWords();
Line 108 ⟶ 93:
}
 
async displayNextWorddisplayNextWordAndNavigate() {
if (this.currentIndex >= this.words.length) {
await this.fetchWords();
Line 118 ⟶ 103:
this.typoDisplayElement.textContent = `Typo: ${currentWord.typo}`;
this.articleNameElement.textContent = `Article: ${currentWord.articleName}`;
}
await this.loadWikipediaArticlenavigateToWikipedia(currentWord.articleName);
#article-content {
this.currentIndex++;
 
await this.loadWikipediaArticle(currentWord.articleName);
 
if (this.currentIndex >= this.words.length) {
Line 131 ⟶ 117:
this.typoDisplayElement.textContent = '';
this.articleNameElement.textContent = '';
this.articleContentElement.textContent = '';
this.articleLinkElement.href = '';
this.articleLinkElement.textContent = '';
}
 
Line 139 ⟶ 122:
}
 
async loadWikipediaArticlenavigateToWikipedia(articleName) {
const encodedArticleName = encodeURIComponent(articleName.replace(/ /g, '_'));
const apiUrl = `https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro=1&explaintext=1&titles=${encodedArticleName}&origin=*`;
const articleUrl = `https://en.wikipedia.org/wiki/${encodedArticleName}`;
window.open(articleUrl, '_blank');
 
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
const extract = pages[pageId].extract;
 
this.articleContentElement.textContent = extract || 'No extract available for this article.';
this.articleLinkElement.href = articleUrl;
this.articleLinkElement.textContent = 'View full article on Wikipedia';
} catch (error) {
console.error('Error fetching Wikipedia article:', error);
this.articleContentElement.textContent = `Error loading article: ${error.message}`;
this.articleLinkElement.href = articleUrl;
this.articleLinkElement.textContent = 'Try viewing on Wikipedia';
}
}