Skip to content

Instantly share code, notes, and snippets.

@pajecawav
Last active July 19, 2022 19:39
Show Gist options
  • Save pajecawav/015fba13326b12a4b0f5672345efeb8c to your computer and use it in GitHub Desktop.
Save pajecawav/015fba13326b12a4b0f5672345efeb8c to your computer and use it in GitHub Desktop.
Yandex Music media controls
// ==UserScript==
// @name yandex-music-media-controls
// @namespace http://tampermonkey.net/
// @version 0.0.1
// @description Integrate Yandex Music with OS media controls
// @author pajecawav
// @match https://music.yandex.ru/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=music.yandex.ru
// @grant none
// @source https://gist.github.com/pajecawav/015fba13326b12a4b0f5672345efeb8c
// @updateURL https://gist.githubusercontent.com/pajecawav/015fba13326b12a4b0f5672345efeb8c/raw
// @downloadURL https://gist.githubusercontent.com/pajecawav/015fba13326b12a4b0f5672345efeb8c/raw
// ==/UserScript==
(() => {
const LOAD_DELAY = 5000;
if (!("mediaSession" in navigator)) {
return;
}
function log(...values) {
console.log("[yandex-music-media-session]", ...values);
}
const api = window.externalAPI;
function play() {
log("Playing");
api.togglePause(false);
}
function pause() {
log("Pausing");
api.togglePause(true);
}
function nextTrack() {
log("Skipping to the next track");
api.next();
}
function prevTrack() {
log("Skipping to the previous track");
api.prev();
}
function updateMetadata() {
log("Updating metadata");
const track = api.getCurrentTrack();
navigator.mediaSession.metadata = new MediaMetadata({
title: track.title,
artist: track.artists.map(artist => artist.title).join(", "),
});
}
setTimeout(() => {
navigator.mediaSession.setActionHandler("play", play);
navigator.mediaSession.setActionHandler("pause", pause);
navigator.mediaSession.setActionHandler("nexttrack", nextTrack);
navigator.mediaSession.setActionHandler("previoustrack", prevTrack);
api.on(api.EVENT_TRACK, updateMetadata);
log("Attached event handlers");
}, LOAD_DELAY);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment