User:Polygnotus/Scripts/VEbutton.js

// Add a custom button to Wikipedia's Visual Editor

// Add this code to your common.js page on Wikipedia

// (e.g., https://en.wikipedia.org/wiki/User:YourUsername/common.js)

// Wait for the VisualEditor to be ready

mw.loader.using(['ext.visualEditor.desktopArticleTarget']).then(function() {

mw.hook('ve.activationComplete').add(function() {

console.log('VE activation hook fired');

// Wait a bit for the toolbar to fully initialize

setTimeout(function() {

addHelloWorldButton();

}, 1000);

// Also add the button when the surface is ready

if (typeof ve !== 'undefined' && ve.init && ve.init.target) {

ve.init.target.on('surfaceReady', function() {

console.log('Surface ready event fired');

addHelloWorldButton();

});

}

});

});

function addHelloWorldButton() {

console.log('Attempting to add Hello World button');

// Check if our button already exists to avoid duplicates

if ($('.oo-ui-tool-name-helloWorldTool').length) {

console.log('Hello World button already exists');

return;

}

// Create a proper new group for our button

var $toolGroup = $('

')

.addClass('ve-ui-toolbar-group-hello oo-ui-widget oo-ui-toolGroup oo-ui-barToolGroup oo-ui-widget-enabled')

.attr('title', 'Hello World Button');

var $toolsContainer = $('

')

.addClass('oo-ui-toolGroup-tools oo-ui-barToolGroup-tools oo-ui-toolGroup-enabled-tools')

.appendTo($toolGroup);

// Create the button itself matching other buttons' structure

var $button = $('')

.addClass('oo-ui-widget oo-ui-iconElement oo-ui-tool-with-icon oo-ui-tool oo-ui-tool-name-helloWorldTool oo-ui-widget-enabled')

.appendTo($toolsContainer);

// Create the link element

var $link = $('')

.addClass('oo-ui-tool-link')

.attr('role', 'button')

.attr('tabindex', '0')

.attr('title', 'Hello World Button')

.appendTo($button);

// Add the icon structure

$('')

.addClass('oo-ui-tool-checkIcon oo-ui-widget oo-ui-widget-enabled oo-ui-iconElement oo-ui-iconElement-icon oo-ui-icon-check oo-ui-labelElement-invisible oo-ui-iconWidget')

.appendTo($link);

$('')

.addClass('oo-ui-iconElement-icon oo-ui-icon-star')

.appendTo($link);

$('')

.addClass('oo-ui-tool-title')

.text('Hello')

.appendTo($link);

// Add click event to show alert

$button.on('click', function(e) {

e.preventDefault();

e.stopPropagation();

alert('hello world');

});

// Insert our group at an appropriate location in the toolbar

// Find the structure or insert group to add after

var $insertPosition = $('.ve-ui-toolbar-group-structure, .ve-ui-toolbar-group-format').last();

if ($insertPosition.length) {

$toolGroup.insertAfter($insertPosition);

console.log('Button added successfully after', $insertPosition.attr('class'));

} else {

// Fallback: add to main toolbar

$('.oo-ui-toolbar-tools').first().append($toolGroup);

console.log('Button added to main toolbar');

}

}