User:K599/TwitchPlayer.js

From Miraheze Meta, Miraheze's central coordination wiki

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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
//Author: K599 / Kelvs599

//Code based on https://dev.fandom.com/wiki/MediaWiki:YoutubePlayer/code.js

//Loading this JavaScript allows Twitch live streams/videos to be embedded. Go to your MediaWiki:Common.js, or wherever you're loading your JS, and either copy this page's code or insert the following line:
//mw.loader.load('https://meta.miraheze.org/w/index.php?title=User:K599/TwitchPlayer.js&action=raw&ctype=text/javascript');

//You embed by inserting the following code:
//<div class="twitchplayer" data-channel=""></div>
//The full list of parameters is as follows:
//<div class="twitchplayer" data-channel="" data-video="" data-collection="" data-width="" data-height="" data-time="" data-autoplay="" data-muted=""></div>
//Explanations for each parameter can be found on https://dev.twitch.tv/docs/embed/video-and-clips (note that this script sets "parent" automatically)
//Default width and height is 620x378.

mw.hook('wikipage.content').add(function($content) {
    $content.find('.twitchplayer:not(.loaded)').each(function() {
        var $this = $(this),
            data = $this.data(),
            uri = new mw.Uri('https://player.twitch.tv/'),
            width = typeof data.width === 'number' ? data.width + 'px' : String(data.width || '').trim(),
            height = typeof data.height === 'number' ? data.height + 'px' : String(data.height || '').trim();

        uri.query = {
            channel: String(data.channel || '').trim(),
            video: String(data.video || '').trim(),
            collection: String(data.collection || '').trim(),
            autoplay: String(data.autoplay ?? '').trim(),
            muted: String(data.muted ?? '').trim(),
            time: String(data.time || '').trim(),
            parent: mw.config.get('wgServerName')
        };

        $this.html(
            $('<iframe>', {
                src: uri.toString(),
                style: 'width: ' + (width ? width : height ? 'calc(' + height + ' * 310 / 189)' : '620px') + '; height: ' + (height ? height : width ? 'calc(' + width + ' * 189 / 310)' : '378px') + ';',
                frameborder: '0',
                scrolling: 'no',
                allowfullscreen: 'true'
            })
        ).addClass('loaded');
    });
});