document.addEventListener('DOMContentLoaded', function() {
// Initialize UI elements
const startButton = document.getElementById('startScraping');
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
const progressPercent = document.getElementById('progressPercent');
const articlesFound = document.getElementById('articlesFound');
const articlesSkipped = document.getElementById('articlesSkipped');
const currentVolume = document.getElementById('currentVolume');
const logMessages = document.getElementById('logMessages');
// Data storage
let articlesData = [];
let keywordsData = [];
// Start scraping from CrossRef API
startButton.addEventListener('click', async function() {
progressContainer.classList.remove('hidden');
// Reset UI and data
progressBar.style.width = '0%';
progressPercent.textContent = '0%';
articlesFound.textContent = '0';
articlesSkipped.textContent = '0';
logMessages.innerHTML = '';
articlesData = [];
keywordsData = [];
addLogMessage('Starting metadata extraction from CrossRef API...');
try {
// Fetch data from CrossRef API
const response = await fetch('https://api.crossref.org/journals/2075-4701/works?rows=100&mailto=your@email.com');
const data = await response.json();
if (data.message && data.message.items) {
processArticles(data.message.items);
} else {
addLogMessage('Error: No articles found in API response');
}
} catch (error) {
addLogMessage(`Error fetching data: ${error.message}`);
}
});
function processArticles(articles) {
articles.forEach((article, index) => {
// Process each article
const articleData = {
title: article.title ? article.title[0] : 'No title',
authors: article.author ?
article.author.map(a => `${a.given} ${a.family}`).join('; ') : 'No authors',
year: article.created ?
new Date(article.created['date-time']).getFullYear() : 'No year',
reads: article.is_referenced_by_count || 0,
citations: article.reference_count || 0,
keywords: article.subject ? article.subject.join(', ') : 'No keywords',
abstract: article.abstract ?
article.abstract.replace(/<[^>]+>/g, '') : 'No abstract available',
doi: article.DOI ? `https://doi.org/${article.DOI}` : 'No DOI',
url: article.URL || 'No URL'
};
articlesData.push(articleData);
// Process keywords separately with proper checks
if (article.subject && Array.isArray(article.subject)) {
article.subject.forEach(keyword => {
if (keyword && typeof keyword === 'string') {
keywordsData.push({
articleTitle: articleData.title,
keyword: keyword.trim()
});
}
});
}
// Update UI
articlesFound.textContent = articlesData.length;
progressBar.style.width = `${((index + 1) / articles.length) * 100}%`;
progressPercent.textContent = `${Math.round(((index + 1) / articles.length) * 100)}%`;
addLogMessage(`Processed: "${articleData.title}"`);
});
// Finalize
progressBar.style.width = '100%';
progressPercent.textContent = '100%';
addLogMessage(`Extraction completed! Processed ${articlesData.length} articles.`);
// Generate exports
generateExports();
}
function generateExports() {
// Create CSV content
// Enhanced CSV generation with all fields
const articlesCSV = convertToCSV(articlesData, [
'title', 'authors', 'year', 'reads', 'citations',
'keywords', 'abstract', 'doi', 'url'
]);
const keywordsCSV = convertToCSV(keywordsData, ['articleTitle', 'keyword']);
// Create download links
createDownloadLink('articles_export.csv', articlesCSV);
createDownloadLink('keywords_export.csv', keywordsCSV);
addLogMessage('Exports ready for download:');
addLogMessage(`Download Articles (${articlesData.length} records, CSV)`);
addLogMessage(`Download Keywords (${keywordsData.length} records, CSV)`);
// Add event listeners to download buttons
document.getElementById('articlesDownload').addEventListener('click', () => {
downloadCSV('articles_export.csv', articlesCSV);
});
document.getElementById('keywordsDownload').addEventListener('click', () => {
downloadCSV('keywords_export.csv', keywordsCSV);
});
}
function convertToCSV(data, headers) {
if (data.length === 0) return headers.join(',') + '\n';
const rows = data.map(row =>
headers.map(fieldName =>
JSON.stringify(row[fieldName], (key, value) =>
value === null ? '' : value
)
).join(',')
);
return [headers.join(','), ...rows].join('\n');
}
function createDownloadLink(filename, content) {
const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
return URL.createObjectURL(blob);
}
function downloadCSV(filename, content) {
const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function addLogMessage(message) {
const now = new Date();
const timeString = now.toLocaleTimeString();
const messageElement = document.createElement('div');
messageElement.innerHTML = `[${timeString}] ${message}`;
logMessages.appendChild(messageElement);
logMessages.scrollTop = logMessages.scrollHeight;
}
});