javascripttwitch

How does Twitch keep a persistent video window over several pages?


Twitch has introduced a functionality that, when you've opened a stream page and navigate to a different part of the site, allows the video to keep playing in the bottom left corner without any interruption. This even works when pressing the back button in the browser and only breaks when closing the tab or manually typing in the URL you want to go to (e.g. https://www.twitch.tv/directory/discover).

I've been trying to figure out how this is being done. The video is embedded into a div with the class "js-player-persistent", so I assume it has something to do with a JavaScript and getting data from the session storage, but I'm unsure how much effort this requires specifically.


Solution

  • Twitch is built on EmberJS on the front end making it a Single Page Application (SPA). This allows them to not have to reload the page as you navigate, they simply utilize AJAX to load in the data needed to show the next page in a prescribed window. This is accomplished by the browser's pushState API or the hashbang implementation for browsers that don't utilize pushState.

    Looking at their implementation of it, they likely have a hook that looks for navigation changes, before it happens, off the video player and at that time create a DOM element in that corner and put the video in it, then they proceed with changing the main page to wherever you are going.

    This is fairly easily done in most SPA front ends like Angular, React, Ember, Vue, etc. and is a major bonus to them.