Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Common.js: Difference between revisions

MediaWiki interface page
Add CSV export button above every wikitable on all content pages
 
Export button only on tables with caption (numeric data tables), not descriptive ones
Line 1: Line 1:
/* ================================================================
/* ================================================================
   CSV Export Button — injects "⬇ Export CSV" above every .wikitable
   CSV Export Button — injects "⬇ Export CSV" only above wikitables
   on content pages. Clicking downloads the table as a .csv file.
  that have a <caption> element (data tables with |+ in wikitext).
   These are the numeric/calculable tables (costs, times, power…).
  Descriptive tables (Building/Function, Strengths/Weaknesses…)
  have no caption and are left untouched.
   ================================================================ */
   ================================================================ */
mw.hook('wikipage.content').add(function ($content) {
mw.hook('wikipage.content').add(function ($content) {
     var pageName = mw.config.get('wgTitle') || 'export';
     var pageName = mw.config.get('wgTitle') || 'export';
     var safeTitle = pageName.replace(/ /g, '_');
     var safeTitle = pageName.replace(/ /g, '_');
    var exportIndex = 0;


     $content.find('table.wikitable').each(function (tableIndex) {
     $content.find('table.wikitable').each(function () {
         var $table = $(this);
         var $table = $(this);


         // Build button
         // Only add button if the table has a <caption>
        if ($table.find('caption').length === 0) return;
 
        exportIndex++;
         var $btn = $('<button>')
         var $btn = $('<button>')
             .text('⬇ Export CSV')
             .text('⬇ Export CSV')
Line 33: Line 40:
                     var line = [];
                     var line = [];
                     cells.each(function () {
                     cells.each(function () {
                        // Get text, collapse whitespace
                         var txt = $(this).text().replace(/\s+/g, ' ').trim();
                         var txt = $(this).text().replace(/\s+/g, ' ').trim();
                        // Escape quotes, wrap in quotes if contains comma or quote
                         if (txt.indexOf(',') !== -1 || txt.indexOf('"') !== -1) {
                         if (txt.indexOf(',') !== -1 || txt.indexOf('"') !== -1 || txt.indexOf('\n') !== -1) {
                             txt = '"' + txt.replace(/"/g, '""') + '"';
                             txt = '"' + txt.replace(/"/g, '""') + '"';
                         }
                         }
                         line.push(txt);
                         line.push(txt);
                     });
                     });
                     if (line.length > 0) {
                     if (line.length > 0) csv.push(line.join(','));
                        csv.push(line.join(','));
                    }
                 });
                 });


                 var csvContent = csv.join('\n');
                 var blob = new Blob([csv.join('\n')], { type: 'text/csv;charset=utf-8;' });
                var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                 var url = URL.createObjectURL(blob);
                 var url = URL.createObjectURL(blob);
                 var suffix = tableIndex > 0 ? '_' + (tableIndex + 1) : '';
                 var suffix = exportIndex > 1 ? '_' + exportIndex : '';
                var filename = safeTitle + suffix + '.csv';
                 var $a = $('<a>').attr('href', url).attr('download', safeTitle + suffix + '.csv').css('display','none');
 
                 var $a = $('<a>')
                    .attr('href', url)
                    .attr('download', filename)
                    .css('display', 'none');
                 $('body').append($a);
                 $('body').append($a);
                 $a[0].click();
                 $a[0].click();
Line 62: Line 59:
             });
             });


         // Wrap button in a div and insert before the table
         $table.before($('<div>').css('margin', '0 0 2px 0').append($btn));
        var $wrapper = $('<div>').css('margin', '0 0 2px 0').append($btn);
        $table.before($wrapper);
     });
     });
});
});

Revision as of 20:46, 17 May 2026

/* ================================================================
   CSV Export Button — injects "⬇ Export CSV" only above wikitables
   that have a <caption> element (data tables with |+ in wikitext).
   These are the numeric/calculable tables (costs, times, power…).
   Descriptive tables (Building/Function, Strengths/Weaknesses…)
   have no caption and are left untouched.
   ================================================================ */
mw.hook('wikipage.content').add(function ($content) {
    var pageName = mw.config.get('wgTitle') || 'export';
    var safeTitle = pageName.replace(/ /g, '_');
    var exportIndex = 0;

    $content.find('table.wikitable').each(function () {
        var $table = $(this);

        // Only add button if the table has a <caption>
        if ($table.find('caption').length === 0) return;

        exportIndex++;
        var $btn = $('<button>')
            .text('⬇ Export CSV')
            .attr('title', 'Download this table as a CSV file')
            .css({
                cursor: 'pointer',
                background: '#1e1e1e',
                color: '#e07000',
                border: '1px solid #e07000',
                borderRadius: '4px',
                padding: '3px 12px',
                fontSize: '0.82em',
                fontWeight: 'bold',
                marginBottom: '4px',
                display: 'inline-block'
            })
            .on('click', function () {
                var rows = $table.find('tr');
                var csv = [];
                rows.each(function () {
                    var cells = $(this).find('th, td');
                    var line = [];
                    cells.each(function () {
                        var txt = $(this).text().replace(/\s+/g, ' ').trim();
                        if (txt.indexOf(',') !== -1 || txt.indexOf('"') !== -1) {
                            txt = '"' + txt.replace(/"/g, '""') + '"';
                        }
                        line.push(txt);
                    });
                    if (line.length > 0) csv.push(line.join(','));
                });

                var blob = new Blob([csv.join('\n')], { type: 'text/csv;charset=utf-8;' });
                var url = URL.createObjectURL(blob);
                var suffix = exportIndex > 1 ? '_' + exportIndex : '';
                var $a = $('<a>').attr('href', url).attr('download', safeTitle + suffix + '.csv').css('display','none');
                $('body').append($a);
                $a[0].click();
                $a.remove();
                setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
            });

        $table.before($('<div>').css('margin', '0 0 2px 0').append($btn));
    });
});