Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Wikipedia QuickSurveys Tracker for common.js// Fetches active surveys and posts them to your userpage(function(){'use strict';// ConfigurationconstQUICKSURVEYS_URL='https://en.wikipedia.org/w/load.php?modules=ext.quicksurveys.lib&debug=true';constMEDIAWICK_BASE_URL='https://en.wikipedia.org/wiki/MediaWiki:';// Function to extract survey data from the loaded modulefunctionextractSurveyData(moduleText){try{// Look for the surveyData.json content in the moduleconstjsonStart=moduleText.indexOf('"resources/ext.quicksurveys.lib/surveyData.json":');if(jsonStart===-1){console.log('No survey data found in module');return[];}// Find the start of the arrayconstarrayStart=moduleText.indexOf('[',jsonStart);if(arrayStart===-1){console.log('No array found in survey data');return[];}// Find the matching closing bracketletbracketCount=0;letarrayEnd=arrayStart;for(leti=arrayStart;i<moduleText.length;i++){if(moduleText[i]==='[')bracketCount++;if(moduleText[i]===']')bracketCount--;if(bracketCount===0){arrayEnd=i+1;break;}}letjsonString=moduleText.substring(arrayStart,arrayEnd);console.log('Extracted JSON length:',jsonString.length);console.log('JSON preview:',jsonString.substring(0,300)+'...');constsurveyData=JSON.parse(jsonString);console.log('Found survey data:',surveyData);constactiveSurveys=[];surveyData.forEach(survey=>{if(survey.name&&survey.coverage>=0){// Show all surveys (including 0% coverage)constsurveyInfo={name:survey.name,coverage:survey.coverage,type:survey.type||'unknown',links:[]};// Check for direct link propertyif(survey.link){surveyInfo.links.push({type:'main',key:survey.link,url:MEDIAWICK_BASE_URL+formatLinkKey(survey.link)});}// Check questions for linksif(survey.questions&&Array.isArray(survey.questions)){survey.questions.forEach(question=>{if(question.link){surveyInfo.links.push({type:'question',key:question.link,url:MEDIAWICK_BASE_URL+formatLinkKey(question.link)});}});}activeSurveys.push(surveyInfo);}});returnactiveSurveys;}catch(error){console.error('Error parsing survey data:',error);return[];}}// Format link key for MediaWiki URL (capitalize first letter of each word)functionformatLinkKey(key){returnkey.split('-').map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join('-');}// Generate wiki markup for the surveysfunctiongenerateSurveyMarkup(surveys){if(surveys.length===0){return'== Wikipedia QuickSurveys ==\n\nNo surveys found in the QuickSurveys module at this time.\n\n';}letmarkup='== Wikipedia QuickSurveys ==\n\n';markup+=`Last updated: ${newDate().toUTCString()}\n\n`;surveys.forEach(survey=>{markup+=`=== ${survey.name} ===\n`;markup+=`* '''Type:''' ${survey.type}\n`;markup+=`* '''Coverage:''' ${(survey.coverage*100).toFixed(1)}%\n`;if(survey.links.length>0){markup+=`* '''MediaWiki Links:'''\n`;survey.links.forEach(link=>{markup+=`** [${link.url}${link.key}] (${link.type})\n`;});}markup+='\n';});returnmarkup;}// Update userpage with survey informationfunctionupdateUserpage(content){constusername=mw.config.get('wgUserName');if(!username){console.error('Not logged in - cannot update userpage');return;}constpageTitle=`User:${username}`;// Get current page contentnewmw.Api().get({action:'query',prop:'revisions',titles:pageTitle,rvprop:'content',rvlimit:1,formatversion:2}).then(data=>{constpages=data.query.pages;if(pages.length===0){console.error('Could not find userpage');return;}letcurrentContent='';if(pages[0].revisions&&pages[0].revisions[0]){currentContent=pages[0].revisions[0].content;}// Remove existing survey section if it existsconstsectionRegex=/== Wikipedia QuickSurveys ==[\s\S]*?(?=\n== |\n----|\n\[\[Category:|\n\{\{|\n<|\n#|$)/;letnewContent=currentContent.replace(sectionRegex,'').trim();// Add new survey sectionif(newContent){newContent+='\n\n'+content;}else{newContent=content;}// Save the pagereturnnewmw.Api().postWithToken('csrf',{action:'edit',title:pageTitle,text:newContent,summary:'Updated active QuickSurveys information via common.js script',minor:true});}).then(()=>{console.log('Successfully updated userpage with survey information');mw.notify('QuickSurveys information updated on your userpage!',{type:'success'});}).catch(error=>{console.error('Error updating userpage:',error);mw.notify('Error updating userpage: '+error.message,{type:'error'});});}// Main function to fetch and process surveysfunctionfetchAndProcessSurveys(){console.log('Fetching QuickSurveys data...');fetch(QUICKSURVEYS_URL).then(response=>response.text()).then(moduleText=>{console.log('Successfully fetched module data');constsurveys=extractSurveyData(moduleText);console.log('Extracted surveys:',surveys);constmarkup=generateSurveyMarkup(surveys);console.log('Generated markup:',markup);updateUserpage(markup);}).catch(error=>{console.error('Error fetching survey data:',error);mw.notify('Error fetching QuickSurveys data: '+error.message,{type:'error'});});}// Add to window for manual executionwindow.updateQuickSurveys=fetchAndProcessSurveys;// Auto-run when on your userpagemw.hook('wikipage.content').add(function(){constcurrentPage=mw.config.get('wgPageName');constusername=mw.config.get('wgUserName');if(username&¤tPage===`User:${username}`){// Only add link if it doesn't already existif($('#update-quicksurveys').length===0){// Add a small link to manually updateconst$link=$('<span style="font-size: 0.8em; margin-left: 1em;">').html('[<a href="#" id="update-quicksurveys">Update QuickSurveys</a>]');$('#firstHeading').append($link);$('#update-quicksurveys').on('click',function(e){e.preventDefault();fetchAndProcessSurveys();});}}});console.log('QuickSurveys tracker loaded. Use window.updateQuickSurveys() to manually update, or visit your userpage and click the update link.');})();