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.
// Add custom buttons to Wikipedia's Visual Editor based on JSON configuration// Add this code to your common.js page on Wikipedia// (e.g., https://en.wikipedia.org/wiki/User:YourUsername/common.js)(function(){// Wait for the VisualEditor to be readymw.loader.using(['ext.visualEditor.desktopArticleTarget','mediawiki.api']).then(function(){// Load JSON configuration and add buttons when VE is activatedmw.hook('ve.activationComplete').add(function(){loadButtonsConfig().then(function(buttons){if(Array.isArray(buttons)&&buttons.length>0){// Register all tools and commandsbuttons.forEach(registerButtonTool);// Add custom toolbar group when surface is readyif(ve.init&&ve.init.target){ve.init.target.on('surfaceReady',function(){addCustomToolbarGroup(buttons);});}}}).catch(function(error){console.error('Failed to load custom buttons configuration:',error);});});});// Load buttons configuration from user's JSON pageasyncfunctionloadButtonsConfig(){constusername=mw.config.get('wgUserName');if(!username)return[];constapi=newmw.Api();try{constresult=awaitapi.get({action:'query',prop:'revisions',titles:`User:${username}/VisualEditorButtonsJSON`,rvslots:'*',rvprop:'content',formatversion:'2',uselang:'content',// Enable cachingsmaxage:'86400',// Cache for 1 daymaxage:'86400'// Cache for 1 day});if(result.query.pages[0].missing){return[];}constcontent=result.query.pages[0].revisions[0].slots.main.content;returnJSON.parse(content);}catch(error){console.error('Error loading buttons configuration:',error);return[];}}// Register a button tool based on configfunctionregisterButtonTool(config){// Add custom icon CSS if URL is providedif(config.icon&&config.icon.startsWith('http')){addCustomIconCSS(config.name,config.icon);}// Create commandconstCommandClass=function(){ve.ui.Command.call(this,config.name);};OO.inheritClass(CommandClass,ve.ui.Command);CommandClass.prototype.execute=function(surface){try{constsurfaceModel=surface.getModel();letcontent=config.insertText;// Handle the string concatenation pattern found in the JSONif(typeofcontent==='string'){// This handles patterns like "text" + ":more" or "pre~~" + "~~post"content=content.replace(/"\s*\+\s*"/g,'');}surfaceModel.getFragment().collapseToEnd().insertContent(content).collapseToEnd().select();returntrue;}catch(error){console.error(`Error executing command ${config.name}:`,error);returnfalse;}};ve.ui.commandRegistry.register(newCommandClass());// Create toolconstToolClass=function(){ve.ui.Tool.apply(this,arguments);};OO.inheritClass(ToolClass,ve.ui.Tool);ToolClass.static.name=config.name;ToolClass.static.title=config.title||config.name;ToolClass.static.commandName=config.name;ToolClass.static.icon=config.icon&&config.icon.startsWith('http')?'custom-'+config.name:(config.icon||'help');ToolClass.prototype.onSelect=function(){this.setActive(false);this.getCommand().execute(this.toolbar.getSurface());};ToolClass.prototype.onUpdateState=function(){this.setActive(false);};ve.ui.toolFactory.register(ToolClass);}// Add custom CSS for iconsfunctionaddCustomIconCSS(name,iconUrl){conststyleId=`custom-icon-${name}`;if(!document.getElementById(styleId)){conststyle=document.createElement('style');style.id=styleId;style.textContent=` .oo-ui-icon-custom-${name} { background-image: url(${iconUrl}) !important; background-size: contain !important; background-position: center !important; background-repeat: no-repeat !important; } `;document.head.appendChild(style);}}// Add a custom toolbar group with our buttonsfunctionaddCustomToolbarGroup(buttons){if(!ve.init.target||!ve.init.target.toolbar){console.warn('Visual editor toolbar not found');return;}// Get button names for the groupconstbuttonNames=buttons.map(config=>config.name);// Define a custom toolbar groupfunctionCustomToolbarGroup(toolFactory,config){ve.ui.ToolGroup.call(this,toolFactory,config);}OO.inheritClass(CustomToolbarGroup,ve.ui.BarToolGroup);CustomToolbarGroup.static.name='customTools';CustomToolbarGroup.static.title='Custom tools';ve.ui.toolGroupFactory.register(CustomToolbarGroup);// Add the group to the toolbarconsttoolbar=ve.init.target.toolbar;// Only add if the group doesn't exist yetif(!toolbar.getToolGroupByName('customTools')){// Get the target index to insert the groupconsttoolGroups=toolbar.getToolGroups();lettargetIndex=-1;for(leti=0;i<toolGroups.length;i++){constgroup=toolGroups[i];if(group.name==='format'||group.name==='structure'){targetIndex=i+1;break;}}// Create the group configconstgroupConfig={name:'customTools',type:'customTools',include:buttonNames};// Add the group at the desired positionif(targetIndex!==-1){toolbar.getItems()[0].addItems([groupConfig],targetIndex);}else{toolbar.getItems()[0].addItems([groupConfig]);}// Rebuild the toolbar to show the new grouptoolbar.rebuild();}}})();