User:Jreppch/LogPagesVisited.js

// Need: Create a log of all wikipedia pages that I read // Scope: This script writes the date, title and url of the currently loaded wikipedia page to a user-subpage (in this case 'Pages_I_have_read') // Created with the aid of Chatgpt4

(function {		'use strict';

const pageTitle = document.querySelector('#firstHeading').innerText; const pageURL = window.location.href; const dateAccessed = new Date.toISOString.split('T')[0]; const pageInfo = dateAccessed + ' ' + pageTitle + ' ' + pageURL + "\n"; const userSubPage = 'User:Jreppch/Pages_I_have_read';

// ---		(async function {		try {			const currentContent = await fetchSubpageContent(userSubPage);			const newContent = currentContent + "\n" + pageInfo;			const editToken = await fetchEditToken;			await updateSubpageContent(userSubPage, newContent, editToken);			console.log('Page added to list');		} 		catch (error) {			console.error('Error:');		}	}) ; //	---	function isUserLoggedIn { return document.querySelector('#pt-logout') !== null; } //	--- Fetch the current content of the user subpage async function fetchSubpageContent(page) { const apiUrl = 'https://en.wikipedia.org/w/api.php'; const params = new URLSearchParams({			action: 'query',			format: 'json',			prop: 'revisions',			titles: page,			rvprop: 'content',			formatversion: '2'		}); const response = await fetch(apiUrl + '?' + params.toString,{			method: 'GET',			credentials: 'include'		}); const data = await response.json; const pages = data.query.pages; return pages[0].revisions && pages[0].revisions[0] ? pages[0].revisions[0].content : ''; } //	--- Retrieve the edit token required for making changes to Wikipedia pages async function fetchEditToken { const apiUrl = 'https://en.wikipedia.org/w/api.php'; const params = new URLSearchParams({			action: 'query',			meta: 'tokens',			format: 'json',		}); const response = await fetch(apiUrl + '?' + params.toString,{				method: 'GET',			credentials: 'include'		}); const data = await response.json; return data.query.tokens.csrftoken; } // --- Update the user subpage with the new content async function updateSubpageContent(page, content, token) { const apiUrl = 'https://en.wikipedia.org/w/api.php'; const editParams = new URLSearchParams({			action: 'edit',			title: page,			token: token,			format: 'json',			text: content,			summary: 'adding page to list'		}); const response = await fetch(apiUrl, {			method: 'POST',			body: editParams,			credentials: 'include'		}); const data = await response.json; if (!data.edit || data.edit.result !== 'Success'){ throw new Error('Failed to add page to list'); }	} });