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 surveys and displays them on 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:';// Track processed pages to prevent duplicatesletprocessedPages=newSet();// 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 only the first letter)functionformatLinkKey(key){returnkey.charAt(0).toUpperCase()+key.slice(1);}// Display survey information in console/notification instead of updating userpagefunctiondisplaySurveyInfo(surveys){if(surveys.length===0){console.log('No surveys found in the QuickSurveys module');mw.notify('No surveys found in QuickSurveys module',{type:'info'});return;}console.log('=== Wikipedia QuickSurveys ===');console.log(`Found ${surveys.length} survey(s):`);letnotificationText=`Found ${surveys.length} survey(s): `;surveys.forEach((survey,index)=>{console.log(`\n${index+1}. ${survey.name}`);console.log(` Type: ${survey.type}`);console.log(` Coverage: ${(survey.coverage*100).toFixed(1)}%`);if(survey.links.length>0){console.log(' MediaWiki Links:');survey.links.forEach(link=>{console.log(` - ${link.key}: ${link.url}`);});}notificationText+=survey.name;if(index<surveys.length-1)notificationText+=', ';});mw.notify(notificationText,{type:'success',autoHide:false});console.log('\n=== End of QuickSurveys ===');}// Main function to fetch and process surveys (for manual checking)functionfetchAndProcessSurveys(){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);displaySurveyInfo(surveys);}).catch(error=>{console.error('Error fetching survey data:',error);mw.notify('Error fetching QuickSurveys data: '+error.message,{type:'error'});});}// Generate survey display when viewing userpagefunctiongenerateSurveyDisplay(){constcurrentPage=mw.config.get('wgPageName');constusername=mw.config.get('wgUserName');constpageKey=`${currentPage}-${Date.now()}`;// Check if we've already processed this page recently (within 1 second)constnow=Date.now();constrecentProcessing=Array.from(processedPages).find(entry=>{const[page,timestamp]=entry.split('-');returnpage===currentPage&&(now-parseInt(timestamp))<1000;});if(recentProcessing){console.log('Survey display recently processed, skipping...');return;}// Prevent duplicate execution by checking for existing elementsif($('#quicksurveys-display-box').length>0){console.log('Survey display already exists, skipping...');return;}// Add to processed pagesprocessedPages.add(`${currentPage}-${now}`);// Clean up old entries (keep only last 10)if(processedPages.size>10){constsortedEntries=Array.from(processedPages).sort();processedPages=newSet(sortedEntries.slice(-10));}console.log('Generating survey display for userpage...');fetch(QUICKSURVEYS_URL).then(response=>response.text()).then(moduleText=>{constsurveys=extractSurveyData(moduleText);if(surveys.length===0){return;}// Double-check that the element doesn't exist (race condition protection)if($('#quicksurveys-display-box').length>0){console.log('Survey display was created while fetching, skipping...');return;}// Create a display box on the userpageconst$surveyBox=$('<div>').attr('id','quicksurveys-display-box').css({'border':'1px solid #a2a9b1','background-color':'#f8f9fa','padding':'10px','margin':'10px 0','border-radius':'3px'}).html('<strong>Wikipedia QuickSurveys</strong><br>');surveys.forEach(survey=>{$surveyBox.append(`<div style="margin: 5px 0;"> <strong>${survey.name}</strong> (${survey.type}, ${(survey.coverage*100).toFixed(1)}% coverage) </div>`);if(survey.links.length>0){survey.links.forEach(link=>{$surveyBox.append(`<div style="margin-left: 15px; font-size: 0.9em;"> → <a href="${link.url}" target="_blank">${link.key}</a> </div>`);});}});// Insert after the first paragraph or at the topconst$content=$('#mw-content-text');const$firstPara=$content.find('p').first();if($firstPara.length){$firstPara.after($surveyBox);}else{$content.prepend($surveyBox);}}).catch(error=>{console.error('Error fetching survey data for display:',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}`){// Use setTimeout to ensure DOM is ready and avoid race conditionssetTimeout(()=>{// Auto-generate survey display on userpagegenerateSurveyDisplay();// 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">Check QuickSurveys</a>]');$('#firstHeading').append($link);$('#update-quicksurveys').on('click',function(e){e.preventDefault();fetchAndProcessSurveys();});}},100);// Small delay to ensure DOM is ready}});console.log('QuickSurveys tracker loaded. Use window.updateQuickSurveys() to manually check, or visit your userpage to see surveys displayed automatically.');})();