Responsive website embedding

Here’s a script I put together on CodePen.

Class: TwitchEmbed

Usage:

  • Options

    • clientID - required - A valid Twitch app client ID for the instance to use in API requests.
    • channelID - optional if channelLogin is supplied - The user ID of a Twitch account to embed.
    • channelLogin - optional if channelID is supplied - The user login of a Twitch account to embed.
    • updateLoopTime - defaults to 300000 - How long between updating the live status in milliseconds.
    • embedParent - A DOM element.
    • autoEmbed- defaults to true - Automatically embed to embedParent if supplied.
    • muted - defaults to false - The embed starts muted.
    • autoplay - defaults to true - The embed plays immediately.
    • width - defaults to 640 - The width of the embed.
    • height - defaults to 360 - The height of the embed.
  • Methods you care might about

    • on - (eventName, callback) - Simple event emitter. Used to make your own code activate when the TwitchEmbed instance detects that the channel is live.
    • off - (eventName, callback) - Remove event callback that was previously added.
    • createEmbed - This method will construct an iframe element and append it to the embedParent from the options.
    • removeEmbed - Removes the current iframe embed.
    • updateLiveStatus - Force the instance to update the live status and possibly emit a change.
    • update - The preferred way to update the live status, especially to automatically embed and prevent overlapping updates.
    • startUpdateLoop - Start a timeout loop for updateLoopTime milliseconds, supplied in the options.
    • stopUpdateLoop - Stop that update loop at any time.
  • Events

    • online / live - Channel is online/live.
    • offline - Channel is offline.

Example

<div id="embed-attach"></div>
let te = new TwitchEmbed({
		clientID: 'some valid client ID',
		// channelID: '19571641', // an ID
		channelLogin: 'bobross', // or a login
		autoEmbed: true,
		embedParent: document.getElementById('embed-attach'),
		muted: true,
		autoplay: true,
		width: 480,
		height: 270
	});

te.on('online', stream => {
    console.log('Stream started', (Date.now() - new Date(started_at)) / 1000 / 60 / 60, 'hours ago');
});

te.on('offline', () => {
    console.log('Stream ended');
});
1 Like