Jump to content

MediaWiki:Gadget-copyTable.js

From Insurer Brain
Revision as of 14:49, 9 June 2026 by Wikilah admin (talk | contribs) (Created page with "* * Gadget: CopyTable * Adds a "Copy" button above every wikitable. * Copies content as TSV (tab-separated values) for pasting into Excel / Sheets.: mw.hook( 'wikipage.content' ).add( function ( $content ) { $content.find( 'table.wikitable' ).not( '.copy-table-added' ).each( function () { var $table = $( this ).addClass( 'copy-table-added' ); var $btn = $( '<button>' ) .addClass( 'copy-table-btn' ) .text( '\uD83D\uDCCB...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.
/**
 * Gadget: CopyTable
 * Adds a "Copy" button above every wikitable.
 * Copies content as TSV (tab-separated values) for pasting into Excel / Sheets.
 */
mw.hook( 'wikipage.content' ).add( function ( $content ) {
    $content.find( 'table.wikitable' ).not( '.copy-table-added' ).each( function () {
        var $table = $( this ).addClass( 'copy-table-added' );

        var $btn = $( '<button>' )
            .addClass( 'copy-table-btn' )
            .text( '\uD83D\uDCCB Copy table' )               // 📋 emoji
            .attr( 'title', 'Copy as tab-separated values' )
            .on( 'click', function () {
                var tsv = tableToTSV( $table[ 0 ] );
                navigator.clipboard.writeText( tsv ).then( function () {
                    $btn.text( '\u2713 Copied!' );             // ✓
                    setTimeout( function () {
                        $btn.text( '\uD83D\uDCCB Copy table' );
                    }, 2000 );
                } );
            } );

        $table.before( $btn );
    } );
} );

function tableToTSV( table ) {
    var lines = [];
    $( table ).find( 'tr' ).each( function () {
        var cells = [];
        $( this ).find( 'th, td' ).each( function () {
            cells.push( $( this ).text().trim().replace( /[\t\n\r]+/g, ' ' ) );
        } );
        lines.push( cells.join( '\t' ) );
    } );
    return lines.join( '\n' );
}