MediaWiki:Common.js
MediaWiki interface page
More actions
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* ================================================================
CSV Export Button — injects "⬇ Export CSV" above every .wikitable
on content pages. Clicking downloads the table as a .csv file.
================================================================ */
mw.hook('wikipage.content').add(function ($content) {
var pageName = mw.config.get('wgTitle') || 'export';
var safeTitle = pageName.replace(/ /g, '_');
$content.find('table.wikitable').each(function (tableIndex) {
var $table = $(this);
// Build button
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 () {
// Get text, collapse whitespace
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 || txt.indexOf('\n') !== -1) {
txt = '"' + txt.replace(/"/g, '""') + '"';
}
line.push(txt);
});
if (line.length > 0) {
csv.push(line.join(','));
}
});
var csvContent = csv.join('\n');
var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
var url = URL.createObjectURL(blob);
var suffix = tableIndex > 0 ? '_' + (tableIndex + 1) : '';
var filename = safeTitle + suffix + '.csv';
var $a = $('<a>')
.attr('href', url)
.attr('download', filename)
.css('display', 'none');
$('body').append($a);
$a[0].click();
$a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
});
// Wrap button in a div and insert before the table
var $wrapper = $('<div>').css('margin', '0 0 2px 0').append($btn);
$table.before($wrapper);
});
});