danielrparks / Newgrounds MediaSession

// ==UserScript==
// @name        Newgrounds MediaSession
// @namespace   https://gitlab.com/danielrparks
// @description Add MediaSession API support to the Newgrounds Audio Player
// @copyright   2023, Daniel Parks (https://gitlab.com/danielrparks)
// @license     MIT; https://mit-license.org/
// @match       https://*.newgrounds.com/*
// @grant       none
// @version     1.1
// @author      Daniel Parks
// @run-at      document-idle
// @updateURL   https://openuserjs.org/meta/danielrparks/Newgrounds_MediaSession.meta.js
// @downloadURL https://openuserjs.org/src/scripts/danielrparks/Newgrounds_MediaSession.user.js
// ==/UserScript==

// ==OpenUserJS==
// @author danielrparks
// ==/OpenUserJS==

	const mapping_NgAudioPlayer_MediaSession = {
		"nexttrack": "next",
		"pause": "pause",
		"play": "play",
		"previoustrack": "previous",
		"stop": "stop",
	}

for (const key in mapping_NgAudioPlayer_MediaSession) {
	navigator.mediaSession.setActionHandler(key, () => NgAudioPlayer.global[mapping_NgAudioPlayer_MediaSession[key]]())
}

ngutils.event.addListener("playlist-item-started", (response) => {
	let artwork = [];
	try {
		let d = document.createElement("div");
		d.innerHTML = response.html;
		let artwork = [{"src": d.querySelector(".ng-apg-media-icon").style.backgroundImage.slice(5, -2)}];
	} catch (e) {
		// pass
	}
	navigator.mediaSession.metadata = new MediaMetadata({
		"title": response.title,
		"artist": response.author,
		"artwork": artwork
	})
})